DEV Community

Dimer Bwimba
Dimer Bwimba

Posted on • Updated on

My Binary Search Solution is better than yours

const binary = (val, arr) => {
  let lower = 0;
  let upper = arr.length - 1;
  while (lower <= upper) {
    console.log("ols");
    const middle = lower + Math.floor((upper - lower) / 2);
    if (val === arr[middle]) {
      return middle;
    }
    if (val < arr[middle]) {
      console.log("right");
      upper = middle - 1;
    } else {
      console.log("left");
      lower = middle + 1;
    }
  }
  return -1;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)