Example 1 — Count the calls
A static counter records the recursion depth.
#include <stdio.h>
static int calls;
static int bs(const int a[], int lo, int hi, int key) {
calls++;
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) return mid;
if (a[mid] < key) return bs(a, mid + 1, hi, key);
return bs(a, lo, mid - 1, key);
}
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
calls = 0;
int r = bs(a, 0, 9, 23);
printf("index of 23: %d (%d calls)\n", r, calls);
calls = 0;
r = bs(a, 0, 9, 24);
printf("index of 24: %d (%d calls)\n", r, calls);
return 0;
} How It Works
- For 23 the ranges are 0-9, 5-9, and 5-6, which is three calls.
- For 24 the search also visits 6-6 and then the empty range 6-5.
- The final empty range hits the base case and returns -1.
