books-grokking_alghorithms/01/binarySearch.js
2025-01-23 08:40:17 +03:00

27 lines
631 B
JavaScript

const binarySearch = (list, item) => {
let startIndex = 0;
let endIndex = list.length - 1;
while (startIndex <= endIndex) {
let midIndex = Math.floor((startIndex + endIndex) / 2);
const candidate = list[midIndex];
if (candidate === item) {
console.log(`Item ${item} found at index ${midIndex}`);
return midIndex;
}
if (candidate > item) {
endIndex = midIndex - 1;
} else {
startIndex = midIndex + 1;
}
};
console.log(`Not found "${item}"`);
return null;
};
const list = [10, 20, 30, 50, 80, 100, 500];
binarySearch(list, 20); // 1
binarySearch(list, 40); // null