Created
October 4, 2020 20:28
-
-
Save shchegol/62d767545c185fc5db7305dfff24aef9 to your computer and use it in GitHub Desktop.
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
Binary search |
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 list = [1, 3, 4, 5, 7, 10]; | |
function binarySearch(list, element) { | |
// code | |
let first = 0; | |
let last = list.length - 1; | |
let position = -1; | |
let found = false; | |
let middle; | |
while (found === false && first <= last) { | |
middle = Math.floor((first + last)/2); | |
if (list[middle] == element) { | |
found = true; | |
position = middle; | |
} else if (list[middle] > element) { | |
last = middle - 1; | |
} else { | |
first = middle + 1; | |
} | |
} | |
return position; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment