Here are sketched solutions to the problems from Levitin Chapter 4 that I suggested as study guides for the first midterm.
int power (int base, int n)
{//computes base raised to n'th power
if (n == 0) return 1;
int halfpower = power(base, n/2);
if (n%2 == 0) return halfpower * halfpower;
else return halfpower * halfpower * base;}
M(0) = 0; M(n) ≤ 2 + M(n/2)
Solution: M(n) ≤ 2 ((log n) + 1)
If n=0, a 2n by 2n square is 1 by 1. If it is missing one square, it has no squares and it is already covered.
If n=1, the square is 2 by 2, and if it is missing one square it is an L-shaped tile. So cover it.
If n > 1, divide the square into four 2n-1 by 2n-1 squares. One of them is missing a square. Place an L-shaped tile so that each of the other three quadrants has a square covered. Now we have four quadrants each with a square missing. Use the n-1 version of the algorithm to cover each of these with L-shaped tiles. With the other L-shaped tile, the original square is now covered.
Run a partition of the numbers with a pivot of zero. After this all negative numbers are to the left of the intersection point, and all positive number are to the right of it, though zeroes can be interspersed throughout. So we've solved this problem, with a single partition and thus O(n) time. You might want to think about the slightly harder problem of getting all the zeroes between the negatives and the positives, still in linear time.
Pick a bolt B arbitrarily. By exhaustive search, find the nut N matching B, using up to n tests. Now compare each nut with B and place it in either a "too big" or "too small" set. Then compare each bolt with N and place it in a "too big" or "too small" set. Observe that each too-big nut matches some too-big bolt, and each too-small nut matches a too-small bolt. So we recurse on the too-big set and on the too-small set. Our total time T(n) is T(k) + T(n-k-1) + O(n), where k is the size of the too-small set. Since (if B was chosen at random) k is equally likely to be any number from 0 through n-1, we have exactly the quicksort recurrence and thus an average-case time of Θ(n log n).
No, binary search cannot be employed easily on a linked list. It requires finding the middle element of an arbitrary list in O(1) time, which is not possible in general.
First find some property that exactly 21 of the pictures have and 21 do not. Ask whether the target has the property and limit consideration to the 21 pictures still possible. Then find a property that 10 of these 21 have and 11 do not, and ask about this. You have now limited the possibilities to at most 11. Another question gets you to at most six, then at most three, then at most two, then at most one. So you can isolate the target in at most six questions. An adversary argument shows that six are necessary -- any strategy with five questions can only be prepared to give 32 of the 42 possible answers.
Last modified 1 October 2003