-
-
Save tcelovsky/dd455f417bd0eb09abd3db54e55b9f4a to your computer and use it in GitHub Desktop.
O(log n) Example
This file contains hidden or 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
const array = [1, 2, 4, 8 ,16, 32, 64, 128, 256]; | |
const number = 128; | |
function binarySearch(array, number) { | |
let startIndex = 0; | |
let endIndex = (array.length) - 1; | |
while (startIndex <= endIndex) { | |
let pivot = Math.floor((startIndex + endIndex)/2); | |
if (array[pivot] === number) { | |
return `Located ${number} at ${pivot}`; | |
} else if (array[pivot] < number) { | |
startIndex = pivot + 1; | |
} else { | |
endIndex = pivot - 1; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment