This code is to implement binary search. However, it did not work and return undefined. I don't know why this went wrong, please help me!
function binarySearch(arr, key) {
let low = 0;
let high = arr.length - 1;
let mid
while (low <= high) {
mid = Math.floor((high + low) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
high = mid - 1;
} else if (arr[mid] > key) {
low = mid + 1;
}
}
// return -1
}
console.log(binarySearch([2, 3, 4, 10, 40], 10));
I see the bug, but I'm going to give you an opportunity to find it first.
Update the code to have an additional console.log statement for each iteration of your search loop.
while (low <= high) {
mid = Math.floor((high + low) / 2);
// ADD THIS LINE
console.log("low=", low, "high=", high, "mid=", mid, "arr[mid]=", arr[mid]);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
high = mid - 1;
} else if (arr[mid] > key) {
low = mid + 1;
}
}
You'll quickly find the bug yourself from observing the console output when you run your program again.