-1

Doing a basic binary search problem, but how do you know if it actually works if you cant see the number that's being returned??

function binarySearch(arr, val) {
    let start = 0;
    let end = arr.length - 1;
  
    while (start <= end) {
      let mid = Math.floor((start + end) / 2);
  
      if (arr[mid] === val) {
        return mid;
      }
  
      if (val < arr[mid]) {
        end = mid - 1;
      } else {
        start = mid + 1;
      }
    }
    return -1;
}

let arr = [1,9,3,4,5,7,2];

binarySearch(arr, 9);
  • Does this answer your question? [What is console.log?](https://stackoverflow.com/questions/4539253/what-is-console-log) – Hanchen Jiang Feb 01 '22 at 23:43

2 Answers2

0

The binary search only works if the array is sort. Use arr.sort()

xdxd
  • 1
0

If you want to debug or just see the print , you can try debugging option in any of the code editor or just add print before return statements with time , to realize what is returned

pmax
  • 26
  • 1