Skip to content

Instantly share code, notes, and snippets.

@jsstrn
Last active November 24, 2021 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsstrn/5ce7d3ac4d0546bb6e9ce412362f25ec to your computer and use it in GitHub Desktop.
Save jsstrn/5ce7d3ac4d0546bb6e9ce412362f25ec to your computer and use it in GitHub Desktop.
A simple binary search algorithm
/*
time: O(log n)
space: O(1)
*/
function binarySearch(value, array) {
let start = 0
let end = array.length
while (end >= start) {
let mid = Math.floor((end - start) / 2) + start
if (array[mid] === value) {
return true
} else if (array[mid] > value) {
end = mid - 1
} else {
start = mid + 1
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment