Let us say that we want to find two numbers in the array A that when added together equal N.
- Sort the array.
- Find the largest number in the array that is less than N/2. Set the index of that number as lower.
- Initialize upper to be lower + 1.
- Set sum = A[lower] + A[upper].
- If sum == N, done.
- If sum < N, increment upper.
- If sum > N, decrement lower.
- If either lower or upper is outside the array, done without any matches.
- Go back to 4.
The sort can be done in O(n log n). The search is done in linear time.
answered 2010-04-19T10:59:22.770