Example 1 — Linear scan versus binary search
Count comparisons to find 70 in a sorted array.
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30, 40, 50, 60, 70, 80};
int key = 70, steps = 0;
for (int i = 0; i < 8; i++) {
steps++;
if (a[i] == key) break;
}
printf("linear: %d comparisons\n", steps);
int lo = 0, hi = 7;
steps = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
steps++;
if (a[mid] == key) break;
if (a[mid] < key) lo = mid + 1;
else hi = mid - 1;
}
printf("binary: %d comparisons\n", steps);
return 0;
} How It Works
- Linear search checks seven elements.
- Binary search checks index 3 (40), index 5 (60), then index 6 (70).
- The gap grows quickly with larger arrays.
