Example 1 — Comparison counts on 16 values
The array holds 0, 2, 4, ... 30.
#include <stdio.h>
static int linear(const int a[], int n, int key) {
int c = 0;
for (int i = 0; i < n; i++) {
c++;
if (a[i] == key) break;
}
return c;
}
static int binary(const int a[], int n, int key) {
int lo = 0, hi = n - 1, c = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
c++;
if (a[mid] == key) break;
if (a[mid] < key) lo = mid + 1;
else hi = mid - 1;
}
return c;
}
int main(void) {
int a[16];
for (int i = 0; i < 16; i++) a[i] = i * 2;
int keys[] = {0, 30, 15};
for (int i = 0; i < 3; i++)
printf("key %d: linear=%d binary=%d\n", keys[i],
linear(a, 16, keys[i]), binary(a, 16, keys[i]));
return 0;
} How It Works
- Key 0 is first, so linear search wins with one comparison.
- Key 30 is last: linear checks all 16, binary needs 5.
- Key 15 is absent: linear scans everything; binary stops after 4.
