Created
December 1, 2021 01:34
-
-
Save JoeCortopassi/fbb5dfe07e44fc99d7118f3341355340 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