/o(log_n).js Secret
Created
July 9, 2021 20:30
Star
You must be signed in to star a gist
O(log n) Example
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
| 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