Binary Search Algorithm

This page provides a simple animation of an algorithm known as binary search. This algorithm is used to find data in a list that has already been sorted. You may see that it works something like the way we look up things in a dictionary, except that it always divides in the middle. The data being searched are located in positions 1 through N of an array, where N is 17 in this example. The algorithm sets low and hi to the ends of this list, and adjusts the endpoints so that the value being sought must always be between them, if it is present at all. It then zeros in on the value until it is found, or until the low and high points pass each other. In that case, the value must be absent.

To run the algorithm, enter a number to look for, and press find. Find things in various parts of the list, and try searching for some things which are not there.

low ← 1
hi ← N
while low ≤ hi do
loc ← (low + hi) / 2
if tofind < arr[loc] then
hi ← loc − 1
else if tofind > arr[loc] then
low ← loc + 1
else
return loc
return "not found"
[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17]
581121273338 42495155586971 839299
To Find:   Faster Slower
Location: