Skip to Content

The Binary Chop

Explanation

The quickest way to find an entry in an ORDERED list is not to search through it from start to end, but to continue splitting the list in two until you reach the entry you are looking for. You begin by setting one pointer to the bottom of the list, another to the top, and a third to mid-way between bottom and top. Then you compare the entry pointed to by this third pointer with the number you are searching for. If your number is bigger you make the bottom equal the pointer, if not make the top equal to it. Then you repeat the process.

Let’s try searching the list of numbers below for the number 14.

bottom>
(1)
3
Set bottom to the lowest position in the list, and top to the highest. Set the pointer to (top+bottom)/2. Is that entry 14? No it’s more, so set top to the current value of pointer and repeat the process.
(2)
6
(3)
8
(4)
14
pointer>
(5)
19
(6)
23
(7)
34
(8)
45
top>
(9)
61
bottom>
(1)
3
Set the pointer to (top+bottom)/2. Is that entry 14? No it’s less, so set bottom to the current value of pointer and try again.
(2)
6
pointer>
(3)
8
(4)
14
top>
(5)
19
(6)
23
(7)
34
(8)
45
(9)
61
(1)
3
Set the pointer to (top+bottom)/2. Is that entry 14? Yes, so exit with the pointer set to the position in the list of the number you are looking for.
(2)
6
bottom>
(3)
8
pointer>
(4)
14
top>
(5)
19
(6)
23
(7)
34
(8)
45
(9)
61

As you can imagine, things are not always as simple as this carefully chosen example. You have to cater for the number not being there, and for the list being empty. There are a number of ways of doing this, but the easiest is to add two numbers of your choice to the list. Make the first entry the most negative number the computer can hold, and the last entry the most positive. This will prevent you from ever trying to search outside the list. Preventing a perpetual loop when the number you want is not in the list is quite simple, just exit when ‘top’ is equal to ‘bottom’+1. If you have not found the number by then, it’s not in the list.

You can use this routine to add numbers to the list in order. If you can’t find the number, you exit with the position it should go to in the list. Just move all the numbers under it down one slot and put the new number in. This works just as well when the list is empty except for your two ‘end markers’.

Have a look at the flowchart on the next page and work through a couple of dry runs with a short list of numbers. You may think that it’s not worth doing it this way and that a ‘linear search’ would be as quick. Try it with a list of 100 numbers. It should take you no more than 7 goes to find the number. The AVERAGE number of comparisons required for a linear search would be 50.

Flowchart of the binary chop search
Last updated on