Skip to content

Instantly share code, notes, and snippets.

@kuznetsovandrey76
Last active May 30, 2020 11:27
Show Gist options
  • Save kuznetsovandrey76/78618337eadd138ba3ae801454308dfd to your computer and use it in GitHub Desktop.
Save kuznetsovandrey76/78618337eadd138ba3ae801454308dfd to your computer and use it in GitHub Desktop.
Бинарный поиск
const binarySearch = (array, item) => {
let low = 0;
let high = array.length - 1;
let iter = 1;
while(low <= high) {
let middle = parseInt((high + low) / 2);
let value = array[middle];
console.log(`${iter}. value: ${value}`)
if (value === item) {
return value;
}
if (value > item) {
high = middle - 1;
} else {
low = middle + 1;
}
iter += 1;
}
return null;
};
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const item = 1;
binarySearch(array, item);
// 1. value: 5
// 2. value: 2
// 3. value: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment