Iterative Binary Search has an undefined right variable
The correct version is:
// Iterative Approach
function binarySearch(arr, val) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let middleIndex = Math.floor((start + end) / 2);
if (arr[middleIndex] === val) {
return middleIndex;
} else if (arr[middleIndex] < val) {
start = middleIndex + 1;
} else {
end = middleIndex - 1;
}
}
return -1;
}
The incorrect terminating condition for the while
loop had start <= right
, where right
wasn’t defined.