Binary Search O(log n) JS
Sep 15, 2023
function indexOfItem(arr, n) {
let first = 0
let last = arr.length - 1
while (first <= last) {
let mid = Math.floor(arr.length / 2)
if (arr[mid] === n) {
return mid
} else if (arr[mid] < n) {
first = mid + 1
} else {
last = mid - 1
}
}
return null
}
// Note that this array is now sorted!
const names = ["Elida Sleight", "Francina Vigneault", "Lucie Hansman", "Nancie Rubalcaba"];
const index = indexOfItem(names, "Lucie Hansman");
console.log(index);