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!

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

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

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

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

Classic DEV Post from Aug 26

What are the hardest programming languages you have ever learned?

For me it was C and Haskell and for completely different reasons. Coming from ...

Sai gowtham
JavaScript developer, Writer & Serverless