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.

/** Searches for a needle in a sorted haystack @param haystack a sorted (in ascending order) array of integers @param needle an integer to be searched for @return true iff there exists i, haystack[i] == needle */ boolean binarySearch(int[] haystack, int needle) { int lower = 0; int upper = haystack.length - 1; while(lower <= upper) { // INV: if there exists i, haystack[i] == needle, // then lower <= i <= upper int middle = (lower + upper) / 2; if(needle == haystack[middle]) { return true; } else if(needle > haystack[middle]) { lower = middle + 1; } else { upper = middle - 1; } } return false; }
bars magnifying-glass caret-down plus minus arrow-right xmark