Last active
May 30, 2020 11:27
-
-
Save kuznetsovandrey76/78618337eadd138ba3ae801454308dfd to your computer and use it in GitHub Desktop.
Бинарный поиск
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 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