Example. Binary Search
[comp1110-1J]
Example. Binary Search
[comp1110-1J]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.