Searching

Consider searching for a given value v in an array of size N. There are 2 basic approaches: sequential search and binary search.

Sequential Search

Sequential search involves looking at each value in turn (i.e., start with the value in array[0], then array[1], etc). The algorithm quits and returns true if the current value is v; it quits and returns false if it has looked at all of the values in the array without finding v. Here's the code:

If the values are in sorted order, then the algorithm can sometimes quit and return false without having to look at all of the values in the array: v is not in the array if the current value is greater than v. Here's the code for this version:

The worst-case time for a sequential search is always O(N).

Binary Search

When the values are in sorted order, a better approach than the one given above is to use binary search. The algorithm for binary search starts by looking at the middle item x. If x is equal to v, it quits and returns true. Otherwise, it uses the relative ordering of x and v to eliminate half of the array (if v is less than x, then it can't be stored to the right of x in the array; similarly, if it is greater than x, it can't be stored to the left of x). Once half of the array has been eliminated, the algorithm starts again by looking at the middle item in the remaining half. It quits when it finds v or when the entire array has been eliminated.

Here's the code for binary search:

The worst-case time for binary search is proportional to log2 N: the number of times N can be divided in half before there is nothing left. Using big-O notation, this is O(log N). Note that binary search in an array is basically the same as doing a lookup in a perfectly balanced binary-search tree (the root of a balanced BST is the middle value). In both cases, if the current value is not the one we're looking for, we can eliminate half of the remaining values.


TEST YOURSELF #1

Why isn't it a good idea to use binary search to find a value in a sorted linked list of values?

solution


Test Yourself #1

Binary search relies on being able to access the kth item in a sequence of values in O(1) time. This is possible when the values are stored in an array, but not when they're stored in a linked list. So binary search using a linked list would usually be much slower than sequential search.