A Pen by idrakimuhamad on CodePen.
Created
October 1, 2021 15:25
-
-
Save idrakimuhamad/223d1cdee9f9ce966ecce794abc5fdb3 to your computer and use it in GitHub Desktop.
Find Sum Pair from given array and target
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 findSum(arr, target) { | |
const sorted = arr.sort() | |
let low = 0; | |
let hi = sorted.length - 1 | |
let found = false | |
while (low < hi) { | |
if (arr[low] + arr[hi] === target) { | |
console.log("Pair found: ", arr[low] + ' + ' + arr[hi]) | |
found = true | |
} | |
if (arr[low] + arr[hi] < target) { | |
low++ | |
} else { | |
hi-- | |
} | |
} | |
if (!found) { | |
console.log('No pair found') | |
} | |
} | |
findSum([1,2,3,4,5,6,7,8], 7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment