Created
April 7, 2022 18:51
-
-
Save JoeCortopassi/9a41d01767190d3bd4fcc2d73c6afa5c to your computer and use it in GitHub Desktop.
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 binarySearch (search, arr) { | |
let lower = 0; | |
let upper = arr.length; | |
while (lower < upper) { | |
let mid = lower + Math.floor((upper - lower) / 2); | |
if (arr[mid] === search) { | |
return mid; | |
} else if (arr[mid] < search) { | |
lower = mid + 1; | |
} else { | |
upper = mid; | |
} | |
} | |
return -1; | |
} | |
const test = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
for (let i=0; i<=test.length; i++) { | |
let foundIndex = binarySearch(i, test); | |
console.log(`test ${i} :: ${foundIndex}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment