Pairs with Sum
Find all pairs within an array which sum to a specified value.
Algorithm:
- Sort array in ascending order
- Set leftIndex = 0 and rightIndex = 0
- Iterate till leftIndex < rightIndex
- Set localSum = array[leftIndex] + array[rightIndex];
- If localSum == sum then
- Print both indices and increase leftIndex and decrease rightIndex by 1
- Else If localSum < sum then
- increase leftIndex by 1
- Else
- decrease rightIndex by 1
Latest Source Code:
Github: PairsWithSum.java
Output:
Pair: (-1, 14) Pair: (0, 13) Pair: (6, 7)