Assume $A$ is an array that contains sorted integers , ie $\forall\ i,j$ where $1 \le i \le j \le |A|$, $A_i \le A_j$. The numbers do not have to be unique, and the task is to check if there is at least one pair of indices $i$ and $j$ where $A_i + A_j = n$. Simple enough, here's an algorithm that does it:
CheckForPair(A, n, i, j):
if i >= j or outOfBound:
return false
v := A[i] + A[j]
if v = n:
return true
if v < n:
return CheckForPair(A, n, i + 1, j)
if v > n:
return CheckForPair(A, n, i, j - 1)
CheckForPair(A, n):
return ChcekForPair(A, n, 1, |A|)
Mathematically,
$$ \begin{align} CheckForPair(A, n, i, j) &= \begin{cases} false & \text{if $i \ge j$ or $i < 1$ or $j > |A|$,} \\ true & \text{if $A_i + A_j = n$,} \\ CheckForPair(A, n, i + 1, j) & \text{if $A_i + A_j < n$,} \\ CheckForPair(A, n, i, j - 1) & \text{if $A_i + A_j > n$} \\ \end{cases} \\ \\ CheckForPair(A, n) &= CheckForPair(A, n, 1, |A|) \end{align} $$
This is an algorithm I have seen somewhere else and I am trying to prove its correctness. For $i$ and $j$ that are on the very ends on the array (ie $i = 1$ and $j = |A|$), it's easy to see why it is correct since:
- if $A_i$ + $A_j < n$, then $i$ must increase because $j$ cannot increase.
- if $A_i$ + $A_j > n$, then $j$ must decrease because $i$ cannot decrease.
However, for $i$ and $j$ that are in between, I fail to see why the above still holds.