If the keys are sorted, we can do much better than checking them one by one. Binary search looks at the middle element and throws away half of the remaining array with a single comparison.
The algorithm
Intuition
Guessing a number between 1 and 100 when told “higher” or “lower”: guess 50, then 25 or 75, and so on. Each guess halves the possibilities, so 7 guesses are always enough for 100 numbers.
Definition 9.3 · Binary search
Binary search looks for a key in an array sorted in ascending order by comparing it with the middle element of the current range [ l o w , h i g h ] [low, high] [ l o w , hi g h ] : if equal, the search succeeds; if smaller, the search continues in [ l o w , m i d − 1 ] [low, mid - 1] [ l o w , mi d − 1 ] ; if larger, in [ m i d + 1 , h i g h ] [mid + 1, high] [ mi d + 1 , hi g h ] ; if the range becomes empty, the search fails.
low = 0, high = n - 1.
While low <= high:
mid = (low + high) / 2 (integer division);
if key == k[mid]: report position mid and stop ;
else if key < k[mid]: high = mid - 1;
else: low = mid + 1.
Report “not found”.
Correction · The binary search algorithm must stop when the key is found
Study material says: In the algorithm of §9.3, the branch if (key=k[mid]) then write "record is at position", mid+1 is followed by no stop, and after the loop Step 5 always writes “Sorry, key value not found”.
Correct version: After reporting the position, the algorithm must stop (or return mid). Only when the loop ends because low > high is the key “not found”.
Why: Without a stop, low and high do not change in the “found” branch, so the loop repeats forever with the same mid; even if it ended, Step 5 would wrongly report failure. Program 9.2 uses a found flag for this, which is the correct idea.
Example 9.4 Searching for 55 in 11 22 33 44 55
Goal. Trace the search for 55 with low = 0, high = 4.
Probe 1. mid = (0 + 4)/2 = 2; k[2] = 33 < 55, so low = 3.
Probe 2. mid = (3 + 4)/2 = 3; k[3] = 44 < 55, so low = 4.
Probe 3. mid = (4 + 4)/2 = 4; k[4] = 55: found at index 4, position 5.
Program check. The program also measures the worst case for larger arrays and searches a descending array.
C · binary_search.c Copy #include <stdio.h>
#include <stdlib.h>
/* Iterative binary search on k[0..n-1] sorted in ascending order.
Returns the index or -1; *probes counts the elements examined. */
int binary_search( const int k [] , int n, int key, int * probes)
{
int low = 0 , high = n - 1 ;
* probes = 0 ;
while (low <= high) {
int mid = low + (high - low) / 2 ; /* same as (low+high)/2, no overflow */
( * probes) ++ ;
if (key == k[mid])
return mid; /* found: STOP here */
else if (key < k[mid])
high = mid - 1 ;
else
low = mid + 1 ;
}
return - 1 ;
}
/* The same search for an array sorted in DESCENDING order:
only the direction of the two comparisons changes. */
int binary_search_desc( const int k [] , int n, int key)
{
int low = 0 , high = n - 1 ;
while (low <= high) {
int mid = low + (high - low) / 2 ;
if (key == k[mid]) return mid;
else if (key > k[mid]) high = mid - 1 ; /* larger keys are to the left */
else low = mid + 1 ;
}
return - 1 ;
}
int main( void )
{
int k [] = { 11 , 22 , 33 , 44 , 55 }, p;
int pos = binary_search(k, 5 , 55 , & p);
printf( "search 55 in 11 22 33 44 55: index %d (position %d), %d probes \n " , pos, pos + 1 , p);
pos = binary_search(k, 5 , 30 , & p);
printf( "search 30: %s after %d probes \n " , pos < 0 ? "not found" : "found" , p);
int d [] = { 90 , 70 , 50 , 30 , 10 };
printf( "descending array, search 30: index %d \n " , binary_search_desc(d, 5 , 30 ));
/* worst case (key larger than every element) for several sizes */
int sizes [] = { 8 , 128 , 256 , 1000 , 100000 };
int * a = malloc( 100000 * sizeof * a);
if (a == NULL ) return 1 ;
for ( int i = 0 ; i < 100000 ; i ++ ) a[i] = 2 * i;
printf( " n linear avg binary worst \n " );
for ( int s = 0 ; s < 5 ; s ++ ) {
binary_search(a, sizes[s], 2 * sizes[s], & p);
printf( "%6d %12d %14d \n " , sizes[s], sizes[s] / 2 , p);
}
free(a);
return 0 ;
}
Output Copy search 55 in 11 22 33 44 55: index 4 (position 5), 3 probes
search 30: not found after 3 probes
descending array, search 30: index 3
n linear avg binary worst
8 4 4
128 64 8
256 128 9
1000 500 10
100000 50000 17
Result. 55 is found after 3 probes; in the worst case binary search needs only 10 probes for 1000 elements and 17 for 100,000.
Efficiency
Each probe halves the range, so after k k k probes at most n / 2 k n/2^k n / 2 k elements remain. The worst case needs ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 probes: O ( log n ) O(\log n) O ( log n ) .
Correction · Comparison table of linear and binary search
Study material says: The table in §9.3 gives the worst-case number of elements examined by binary search as 11 for an array of 1000 elements and 18 for 100,000.
Correct version: The worst case is ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 probes: 10 for n = 1000 n = 1000 n = 1000 (since 2 9 = 512 ≤ 1000 < 1024 = 2 10 2^9 = 512 \le 1000 < 1024 = 2^{10} 2 9 = 512 ≤ 1000 < 1024 = 2 10 ) and 17 for n = 100,000 n = 100{,}000 n = 100 , 000 (since 2 16 = 65,536 ≤ 100,000 < 131,072 2^{16} = 65{,}536 \le 100{,}000 < 131{,}072 2 16 = 65 , 536 ≤ 100 , 000 < 131 , 072 ). The other rows (4, 8, 9 for 8, 128, 256) are correct.
Why: The program above counts the probes for an unsuccessful search larger than every key, which is a worst case, and prints 10 and 17.
Binary search versus linear search
Linear search Binary search Data must be sorted No Yes Works on linked lists Yes No (needs O ( 1 ) O(1) O ( 1 ) access to the middle) Comparisons (worst) n n n ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 Order O ( n ) O(n) O ( n ) O ( log n ) O(\log n) O ( log n ) Best for Small or unsorted data, one-off searches Large sorted arrays searched many times
For an array sorted in descending order (Check Your Progress 2, Q2), only the direction of the comparison changes: if key > k[mid], search the left half (high = mid - 1), otherwise the right half (low = mid + 1); see binary_search_desc above.
Correction · Program 9.2 (binary search)
Study material says: Program 9.2 (§9.3) declares void binary_search(...) but main prints binary_searchy(array, 33, 100) with %d; it reads with scanf("%d", array[i]) after the prompt “Enter the name:”; it writes if (found==1 without a closing parenthesis; and it uses <conio.h> and void main(void).
Correct version: Name the function consistently, make it return the index (or −1) as int, read with scanf("%d", &array[i]), check that the input is sorted (binary search requires it), close the parenthesis, and use standard headers with int main(void).
Why: binary_searchy is undeclared and a void function has no value to print, so the program does not compile. scanf needs the address &array[i]; passing the value is undefined behaviour. Unsorted input makes binary search give wrong answers.
Key idea
Binary search on a sorted array compares the key with the middle element and discards half the range each time, so it needs at most ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 probes: O ( log n ) O(\log n) O ( log n ) .
TEE Exam note
For “write the binary search algorithm and trace it” give the algorithm with the stop on success, a table of (low, mid, high, k[mid]) for each probe, and the complexity with the halving argument. Check Your Progress 2, Q1: (a) the worst-case order of linear search is O ( n ) O(n) O ( n ) , not O ( n / 2 ) O(n/2) O ( n /2 ) : False; (b) linear search is not more efficient than binary search on large sorted data: False; (c) binary search also works on descending order: False.
Common mistake
Using binary search on unsorted data. It will run, but its answers are meaningless.
Common mistake
Writing low = mid or high = mid instead of mid ± 1. The range may then never shrink and the loop never ends.
Key takeaways
Binary search needs sorted data and random access (arrays).
Compare with the middle; go left (high = mid - 1) or right (low = mid + 1); stop when found or when low > high.
Worst case ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 probes: 10 for 1000 elements, 17 for 100,000.
For descending order, reverse the direction of the comparison.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice What is the maximum number of probes binary search needs for a sorted array of 1000 elements?
A 11 B 10 C 500 D 9
Check answer
Show answer Answer: B. 10
⌊ log 2 1000 ⌋ + 1 = 9 + 1 = 10 \lfloor \log_2 1000 \rfloor + 1 = 9 + 1 = 10 ⌊ log 2 1000 ⌋ + 1 = 9 + 1 = 10 . The study material’s table says 11.
Question 2 · multiple choice In a search with low = 6 and high = 11, which index is probed?
A 9 B 7 C 8 D 8.5
Check answer
Show answer Answer: C. 8
( 6 + 11 ) / 2 = 8 (6 + 11)/2 = 8 ( 6 + 11 ) /2 = 8 with integer division.
Question 3 · multiple choice The key is smaller than k[mid]. What is the next step in an ascending array?
A low = mid + 1 B high = mid C low = mid D high = mid − 1
Check answer
Show answer Answer: D. high = mid − 1
The key can only be to the left of mid, and mid itself has been checked. high = mid may cause an endless loop.
Question 4 · multiple choice What does this program print?
C · q9-binary.c Copy #include <stdio.h>
int main( void )
{
int k [] = { 3 , 8 , 15 , 21 , 30 , 42 , 57 , 64 };
int key = 42 , low = 0 , high = 7 , probes = 0 , pos = - 1 ;
while (low <= high) {
int mid = (low + high) / 2 ;
probes ++ ;
if (k[mid] == key) { pos = mid; break ; }
if (key < k[mid]) high = mid - 1 ; else low = mid + 1 ;
}
printf( "pos=%d probes=%d \n " , pos, probes);
return 0 ;
} A pos=5 probes=3 B pos=6 probes=2 C pos=5 probes=2 D pos=5 probes=1
Check answer
Show answer Answer: C. pos=5 probes=2
Probe 1: mid = 3 (21 < 42), low = 4. Probe 2: mid = (4 + 7)/2 = 5, k[5] = 42: found.
Question 5 · multiple choice Why can binary search not be used efficiently on a linked list?
Check answer
Show answer Answer: C. Reaching the middle element of a linked list takes O ( n ) O(n) O ( n ) steps.
Binary search depends on jumping to the middle in O ( 1 ) O(1) O ( 1 ) , which arrays allow and linked lists do not. (Skip lists, Unit 3, solve this.)
Question 6 · short answer
Write the binary search algorithm for an array sorted in descending order (Check Your Progress 2, Q2).
Show worked answer low = 0, high = n − 1. While low ≤ high: mid = (low + high)/2; if key = k[mid], return mid (found, stop); else if key > k[mid], high = mid − 1 (larger keys are on the left in descending order); else low = mid + 1. After the loop, return “not found”. It still needs at most ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 probes.