Binary search algorithm in javascript

This is my implementation

function binarySearch(arr, target) {

  const midpoint = Math.floor(arr.length / 2);

  if (arr[midpoint] === target) return arr[midpoint];
  if (arr[midpoint] < target && arr.length > 1) return binarySearch(arr.slice(midpoint), target);
  if (arr[midpoint] > target && arr.length > 1) return binarySearch(arr.slice(0, midpoint), target);

  return "not found";
}

console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 11)) //11

what is your implementation to binary search algorithm?

Did you find this post useful? Show some love!
DISCUSSION (4)

Tip: You can re-write midpoint as const midpoint = arr.length >> 1

While that might be faster, I think the original might be clearer.

Actually this way you avoid using Math.floor and it's not so bad. Its just a build-in operator

I would agree. Software is written for humans, not computers. Although, interesting, this seems like a premature optimization.

Classic DEV Post from Jun 7

Let's make my website even better

I just finished redesigning my website. It isn't live just yet. I wanted to see what can I do to make it even better.

Sai gowtham
JavaScript developer, Writer & Serverless
Join dev.to