Home > Blockchain >  How to find/print return value of a function?
How to find/print return value of a function?

Time:02-02

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

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related