Last active
November 24, 2021 02:40
-
-
Save jsstrn/5ce7d3ac4d0546bb6e9ce412362f25ec to your computer and use it in GitHub Desktop.
A simple binary search algorithm
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
/* | |
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