Example 1 — Pair with a target sum in a sorted array
Target 15 in 1, 2, 4, 7, 11, 15.
#include <stdio.h>
int main(void) {
int a[] = {1, 2, 4, 7, 11, 15};
int lo = 0, hi = 5, target = 15, steps = 0;
while (lo < hi) {
steps++;
int s = a[lo] + a[hi];
if (s == target) {
printf("%d + %d = %d (indices %d and %d) after %d steps\n",
a[lo], a[hi], target, lo, hi, steps);
return 0;
}
if (s < target) lo++;
else hi--;
}
printf("no pair\n");
return 0;
} How It Works
- 1 + 15 is too large, so
himoves left. - 1 + 11 and 2 + 11 are too small, so
lomoves right twice. - 4 + 11 matches. The nested-loop version would have checked many more pairs.
