Example 1
Suppose that we want to perform a binary search for the value 75 on the
following data.
12 34 47 62 75 87 90
Initially, we want to examine the entire array so the variables bottom and
top are initialized to 0 and 6, the indices of the first and last elements,
respectively while middle is set to (0 + 6) /2 = 3. (In the diagrams, we
use arrows to emphasize the purpose of bottom, middle, and top; they
should not be confused with the arrows that we use for reference variables.)
Since 62 < 75, the item that we are seeking cannot be in the left half of the list. We discard this half of the list by setting bottom to middle + 1.
The middle of the remaining interval is (4 + 6) /2 = 5, as shown in the next diagram.
Since 87 > 75, the value 75 cannot be in the upper half of this sublist so we discard it by setting top to middle - 1. Since bottom and top are now both equal to 4, the value of middle will be (4 + 4) /2 = 4.
Once middle has found the value, the search ends successfully.
|
|