Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Last active July 15, 2021 08:47
Show Gist options
  • Save sagittaracc/f8a292181c499c41a2caf73c1a326ed3 to your computer and use it in GitHub Desktop.
Save sagittaracc/f8a292181c499c41a2caf73c1a326ed3 to your computer and use it in GitHub Desktop.
Search for pairs in sorted array
function searchForPairsBySum(sortedArray, sum) {
var leftIndex = 0;
var rightIndex = sortedArray.length - 1
while (leftIndex !== rightIndex) {
if (sortedArray[leftIndex] + sortedArray[rightIndex] === sum) {
console.log(sortedArray[leftIndex], sortedArray[rightIndex], "Indexes: ", leftIndex, rightIndex);
leftIndex++;
rightIndex++;
}
else if (sortedArray[leftIndex] + sortedArray[rightIndex] > sum) {
rightIndex--;
}
else if (sortedArray[leftIndex] + sortedArray[rightIndex] < sum) {
leftIndex++;
}
}
/**
*
* > searchForPairsBySum([1, 1, 3, 5, 5, 9, 10], 10)
* 1 9 "Indexes: " 0 5
* 1 9 "Indexes: " 1 5
* 5 5 "Indexes: " 3 4
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment