Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I debug this Javascript code for binary search

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));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading