Binary Search
[comp1110-77] - Fabian Muehlboeck
Binary Search
[comp1110-77]- Fabian Muehlboeck
Example 1. Guessing Game
[comp1110-13] - Liam O'Connor, Fabian Muehlboeck
Example 1. Guessing Game
[comp1110-13]- Liam O'Connor, Fabian Muehlboeck
In the lecture, we created a guessing game, choosing a "random" number based on a fair die roll.
Note 2. Bounding our Guesses
[comp1110-14] - Liam O'Connor, Fabian Muehlboeck
Note 2. Bounding our Guesses
[comp1110-14]- Liam O'Connor, Fabian Muehlboeck
If we know that the range of possible answers in Example 1 is \(0\) to \(100\), then we can algorithmically devise a procedure that will always guess the right answer:
- We know that the number is between \(0\) and \(100\). Guess \(50\). We get the report
Smaller!. - We know that the number is between \(0\) and \(49\). Guess \(25\). We get the report
Bigger!. - We know that the number is between \(26\) and \(49\). Guess \(37\). We get the report
Smaller!. - We know that the number is between \(26\) and \(36\). Guess \(31\). We get the report
Bigger!. - We know that the number is between \(32\) and \(36\). Guess \(34\). We succeed.
Following this procedure of always bisecting the possible range means that we will always get the answer in at most \(\log _2 100 \simeq 7\) guesses. In general, this bisecting means that for a range \(0\) to \(n\), we will get the answer in at most \(\log _2 n\) guesses.
Example 3. Binary Search
[comp1110-1J] - Liam O'Connor
Example 3. Binary Search
[comp1110-1J]- Liam O'Connor
If we add a precondition to the spec of contains, that the input array is sorted,
we can use a trick similar to our solution algorithm for our guessing game, which as we saw,
can reduce the amount of iterations of the program from linear in the size of the input to logarithmic.
The idea is that we consistently pick the middle index from the range of possible indices. If the value at this index is our target, we have found what we're looking for, and we're done. If the value at this index is larger than our target, that means our desired index is to the left, and reduces the range of possible indices by half. If it is smaller, then our desired index is to the other half, on the right of the selected midpoint.
This narrows the range of possible indices, which permits us to repeat this technique until we reach single elements.