Last active
July 15, 2021 08:47
-
-
Save sagittaracc/f8a292181c499c41a2caf73c1a326ed3 to your computer and use it in GitHub Desktop.
Search for pairs in sorted array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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