Divide and Conquer

We can search fast through huge sort data via the divide and conquer search method.

Guessing a Secret

Consider the following little game:

  • The computer picks a random integer in [0, 1000].
  • It is up to the user to guess the number.

Suppose making a guess costs $1 and you get $100 for the right guess. Would you play this game?

Suppose now the computer would tell you after each incorrect guess: too low or too high. With same cost and price, would you now play this game?

An example of a session of the game with the too low and too high feedback is shown below.

$ python findsecret.py
Guess number in [0, 1000] : 500
Your guess is too low.
Guess number in [0, 1000] : 750
Your guess is too high.
Guess number in [0, 1000] : 625
Your guess is too high.
Guess number in [0, 1000] : 562
Your guess is too high.
Guess number in [0, 1000] : 531
Your guess is too high.
Guess number in [0, 1000] : 516
Your guess is too high.
Guess number in [0, 1000] : 508
Your guess is too high.
Guess number in [0, 1000] : 504
Your guess is too low.
Guess number in [0, 1000] : 506
found 506 after 9 guesses

The search space is [0, 1000] at the start, in Fig. 38.

_images/fighalvingsearch.png

Fig. 38 Halving the search space in each step.

As shown in Fig. 38, in each step the search space is cut in half. After 10 steps, we are down to the last digit. In every step we recover one bit of the secret.

Exercises

  1. Write an iterative version of binary_search.
  2. Write an iterative version of bisectroot.
  3. The minimum of a list of unsorted numbers is the minimum of the minimum of the first half and the minimum of the second half of the list. Write a function to compute the minimum this way.
  4. Given is a list of lexicographically sorted names. Use divide and conquer to find the name that occurs most frequently in the list.
  5. Develop bisection search to compute the binary representation of a number x, starting at the most significant bit. Use math.log(x,2) to compute the total number of bits needed to represent x.