《编程珠玑》第 4 章──编写正确的程序

习题

2. If the original binary search was too easy for you, try the variant that returns in P the first occurrence of T in the array X (if there are multiple occurrences of T, the original algorithm returns an arbitrary one). Your code should make a logarithmic number of comparisons of array elements; it is possible to do the job in log⁡2N\log _2Nlog2​N such comparisons.

6. [C. Scholten] David Gries calls this the “Coffee Can Problem” in his Science of programming. You are initially given a coffee can that contains some black beans and some white beans and a large pile of “extra” black beans. You then repeat the following process until there is a single bean left in the can.

Randomly select two beans from the can. If they are the same color, throw them both out and insert an extra black bean. If they are different colors, return the white bean to the can and throw out the black.

Prove that the process terminates. What can you say about the color of the final remaining bean as a function of the numbers of black and white beans originally in the can?

7. A colleague faced the following problem in a problem to draw lines on a bitmapped display. An array of N pairs of reals (ai,bi)\left(a_i, b_i\right)(ai​,bi​) defined the N lines yi=aix+biy_i = a_ix + b_iyi​=ai​x+bi​. The lines were ordered in the x-interval [0, 1] in the sense that yi<yi+1y_i < y_{i+1}yi​<yi+1​ for all values of iii between 1 and N-1 and all values of x in [0, 1]:
Less formally, the lines don’t touch in the vertical slabs. Given a point (x, y), where 0≤x≤10\leq x \leq 10≤x≤1, he wanted to determine the two lines that bracket the point. How could he solve the problem quickly?

8. Binary search is fundamentally faster than sequential search: to search an N-element table, it makes roughly log⁡2N\log _2Nlog2​N comparisons while sequential search makes roughly N2\frac{N}{2}2N​. While it is often fast enough, in a few cases binary search must be made faster yet. Althought you can’t reduce the logarighmic number of comparisons made by the algotighm, can you rewrite the binary search code to be faster? For definiteness, assume that you are to search a sorted table of N=1000 integers.