Skip to content

Instantly share code, notes, and snippets.

@AaronFlower
Last active October 26, 2017 02:23
Show Gist options
  • Save AaronFlower/25be912b11f4cec8a249d8d60dae13f8 to your computer and use it in GitHub Desktop.
Save AaronFlower/25be912b11f4cec8a249d8d60dae13f8 to your computer and use it in GitHub Desktop.
Binary Search
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