JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
let c = (...k) => console.log(...k);
// Binary search
let list = [1, 2, 3, 4, 5, 6, 7, 8]; // sorted input
let itemToFind = 17;
let itemIndex = null;
let minIndex = 0;
let maxIndex = list.length - 1;
let halfFun = (min, max) => Math.floor((min + max) / 2);
let halfIndex = halfFun(minIndex, maxIndex);
c(minIndex, maxIndex, '---', halfIndex);
// iterate till half is not possible
// minIndex maxIndex - halfIndex
// 0 7 - 3
// 3 7 - 5
// 5 7 - 6
// 6 7 - 6 (stop here since item not found)
// 6 7 - 6
while (minIndex != halfIndex) {
// case 1 - at minIndex
if (itemToFind == list[minIndex]) {
itemIndex = minIndex;
break;
}
// case 2 - at maxIndex
if (itemToFind == list[maxIndex]) {
itemIndex = maxIndex;
break;
}
// case 3 - at halfIndex
if (itemToFind == list[halfIndex]) {
itemIndex = halfIndex;
break;
}
// shift min/max to haldIndex based on itemToFind value since it's sorted
if (itemToFind > list[halfIndex]) {
minIndex = halfIndex;
} else {
maxIndex = halfIndex;
}
halfIndex = halfFun(minIndex, maxIndex);
c(minIndex, maxIndex, '---', halfIndex);
}
c(itemIndex);