Binary Search
Binary Search

Binary Search works by dividing the data in halves until the desired value is either found or not possibly there. This search only works if the data is already sorted. Here is an example of a search where we are looking for the number 7 in a given sorted array:

Step 1: Find the middle element of the given sorted array.
1 3 4 7 11 12 13 17 20 21 25
Step 2: Compare the value found at the center of the array to the value for which you are looking. In this case:
7 < 12 (desired < current)
So, you call Binary Search again. Only looking at the Elements 1 through 5.
1 3 4 7 11 12 13 17 20 21 25
Step 3: Find the middle element of the remaining portion of the array.
1 3 4 7 11
Step 4: Compare the value found at the center of the remaining array to the value for which you are searching. In this case:
7 > 4 (desired > current)
So you call Binary Search again. This time only looking at Elements 4 through 5.
1 3 4 7 11
Step 5: Find the middle element of the dremaining portion of the array. This time the array is only 2 elements long, which is an even number. Which element will be considered the middle element is determined by the programmer. I choose my middle element to be 7.
7 11
Since the desired element and the current element are equal, we have found what we are looking for and return.

In this example, a linear search would be much easier to code than a binary search and would have only taken a little longer then the binary search. But imagine you have an array of all the social security numbers of all the students at UMBC sorted in ascending order and you had to find one student. Which algorithm would be more efficient?

When we compare Linear and Binary Search, we say that Linear search takes O(n) time while Binary search only takes O(lg n) time, n being the number of elements you start out with. If we pretend to have 1 million sorted elements to search, Linear search could do as many as 1 million comparsions where as Binary Search has to do only 20 comparisons at the most. See the savings?


Main Page
Last Modified 17 October 2000