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 Jan 15

When is it time to leave?

How do you really know when it’s time to call it day and move on?

READ POST
Follow @ky1e_s to see more of their posts in your feed.
Sai gowtham
JavaScript developer, Writer & Serverless
More from @saigowthamr
Intro to Logarithms Big O
#computerscience #javascript #webdev #beginners
Intro to the Big O πŸ‘€
#computerscience #beginners #javascript #career
Trending on dev.to
Introducing Pudl: An Easy to Use JavaScript-Based Static Site Generator
#javascript #pug #sass #staticsitegenerator
Test-Driven React: The Mostly Definitive Guide to Testing React Components
#react #javascript #tdd #testing
Scalable React Components architecture
#react #javascript
Explain XKCD To Me
#mozilla #javascript #browsers #programming
Why you need to know about the Lindy effect, as a developer.
#javascript #webdev #career #discuss
World's Smallest Quine, "Guaranteed"
#quines #c #javascript #codegolf
JavaScript Pro Tips - Code This, NOT That
#javascript
Shine a light on JavaScript performance with Lighthouse
#javascript #webperf #lighthouse #webdev