Last active
May 25, 2017 04:16
-
-
Save jpoechill/f6298d0c6f94b11c478d4c938789ce7d to your computer and use it in GitHub Desktop.
sumOfTwo via. Web
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 sumOfTwo(a, b, v) { | |
a.sort() | |
b.sort() | |
for(i in a) { | |
var target = v - a[i] | |
if (binary_Search(b, target) > -1) { | |
console.log(target) | |
return true | |
} | |
} | |
return false | |
} | |
function binary_Search(items, value){ | |
var firstIndex = 0, | |
lastIndex = items.length - 1, | |
middleIndex = Math.floor((lastIndex + firstIndex)/2); | |
while( items[middleIndex] != value && firstIndex < lastIndex) { | |
if ( value < items[middleIndex] ) { | |
lastIndex = middleIndex - 1; | |
} | |
else if ( value > items[middleIndex] ) { | |
firstIndex = middleIndex + 1; | |
} | |
middleIndex = Math.floor((lastIndex + firstIndex)/2); | |
} | |
return (items[middleIndex] != value) ? -1 : middleIndex; | |
} | |
// var items = [1, 2, 3, 4, 5, 7, 8, 9]; | |
// console.log(binary_Search(items, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment