Skip to content

Instantly share code, notes, and snippets.

@Kirill255
Created May 25, 2019 10:49
Show Gist options
  • Save Kirill255/9abc03b38e70f95c85421946eb55f434 to your computer and use it in GitHub Desktop.
Save Kirill255/9abc03b38e70f95c85421946eb55f434 to your computer and use it in GitHub Desktop.
// бинарный поиск
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function binary_search(num) {
var low = 0;
var high = arr.length - 1;
while (low <= high) {
var middleIndex = Math.round((low + high) / 2);
if (arr[middleIndex] === num) {
return console.log(`Num ${num} — index: ${middleIndex}`);
} else if (arr[middleIndex] > num) {
high = middleIndex - 1;
} else {
low = middleIndex + 1;
}
}
return console.log(`Num ${num} — none!`);
}
binary_search(20);
binary_search(8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment