found a bug in Absolute Beginner’s Guide to Algorithms

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.

1 Like

Wow! You are absolutely right. Thanks for flagging this. I’ve documented it in the errata thread and have also flagged it for correction in future printings.

1 Like