Skip to content

Instantly share code, notes, and snippets.

@shchegol
Created October 4, 2020 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shchegol/62d767545c185fc5db7305dfff24aef9 to your computer and use it in GitHub Desktop.
Save shchegol/62d767545c185fc5db7305dfff24aef9 to your computer and use it in GitHub Desktop.
Binary search
// 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