Last active
October 26, 2017 02:23
-
-
Save AaronFlower/25be912b11f4cec8a249d8d60dae13f8 to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or 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
a = Array.from({length: 15}).map((_,i) => i) | |
function binarySearch(arr, needle) | |
{ | |
let begin = 0, end = arr.length - 1 | |
while (begin <= end) { | |
let mid = Math.floor((end - begin) / 2) + begin | |
if (arr[mid] === needle) { | |
return mid | |
} else if (arr[mid] > needle) { | |
end = mid - 1 | |
} else { | |
begin = mid + 1 | |
} | |
} | |
return -1 | |
} | |
a.forEach((i) => { | |
console.log('binarySearch:', binarySearch(a, i)) | |
}) | |
console.log('binarySearch:', binarySearch(a, -1)) | |
console.log('binarySearch:', binarySearch(a, 99)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment