DEV Community

loading...

My Binary Search Solution is better than yours

Dimer Bwimba
Coding meanπŸ‘:) πŸ₯‡ . Die having memories don't die with just dreams. Take care of your body, it's the only place you have to lv
・Updated on ・1 min read
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

Discussion (0)

Forem Open with the Forem app