I found a bug in your code in your book. The following code:
// Recursive Approach
function binarySearch(arr, val, start = 0, end = arr. {
const middleIndex = Math.floor((start + end) / 2);
if (val === arr[middleIndex]) {
return middleIndex;
}
if (start >= end) {
return -1;
}
if (val < arr[middleIndex]) {
binarySearch(arr, val, start, middleIndex - 1);
} else {
binarySearch(arr, val, middleIndex + 1, end);
}
}
Should be corrected to:
// Recursive Approach
function binarySearch(arr, val, start = 0, end = arr. {
const middleIndex = Math.floor((start + end) / 2);
if (val === arr[middleIndex]) {
return middleIndex;
}
if (start >= end) {
return -1;
}
if (val < arr[middleIndex]) {
return binarySearch(arr, val, start, middleIndex - 1);
} else {
return binarySearch(arr, val, middleIndex + 1, end);
}
}
Make sure to include the return
statement in the recursive calls to binarySearch
to fix the issue.