Code
Linear and binary search
Let's check the table from the theory: how many boxes do the two searches really check?
A second program in the same folder. CMakeLists.txt:
add_executable(p06_search search.c)
search.c
- The array
numbersholds 1000 even numbers: 0, 2, 4, … 1998. A loop fills it (2 * i), so it is already sorted. int linear_search(...)andint binary_search(...)are the two searches from the theory. Both count the boxes they check in the variablechecks.checksis declared outside the functions: it is a global variable, and every function in this file sees it. Avoid that in programs: any function can change it, and it is hard to track down which one did. Here it is only for measuring.mainlooks for four values:int targets[] = {0, 998, 1998, 7};. The compiler works out the size, andsizeoffinds it.assert(pos2 == pos);checks that both searches found the same thing. The search is called before theassert, not inside it (topic 5).
middle = left + (right - left) / 2 is the same as (left + right) / 2, except that the sum can never overflow an int (topic 2).
Run it
Pick p06_search and ▶:
Target Linear Binary
0 1 9
998 500 1
1998 1000 10
7 1000 10
- 0 is the first box: linear search needs one check, while binary search starts in the middle and takes 9 checks to get there.
- 998 is exactly the middle (index 499): binary search finds it at the first try.
- 1998 is the last, and 7 is odd, so it isn't there: linear search checks all 1000, binary search 10.
Binary search doesn't always win, but its worst case is 10, and linear search's is 1000.
Commit: Add linear and binary search.