DEV Community

Clint Maruti
Clint Maruti

Posted on

1

Binary Search - A Simple Code

In my last post in this series, I wrote about Recursion.

Now, if you have just bumped into this post, it follows a series of posts I have been creating. I'm making this in adherence to the Feynman's Technique which is basically just to improve my comprehension level with an approach to teaching what I have learned.

So, I covered a brief intro on Binary Search and also touched on recursion which we will use in writing this algorithm.

We are going to write a function that takes in an array of numbers as its first argument and a key as its second. The function will search through the array using Binary Search and return true if the key exists or false if it doesn't.

function binarySearch(numArray, key){
   let middleIndex = Math.floor(numArray.index / 2)
   let middleElem = numArray[middleIndex]

   if(middleElm === key) return true;
   if(middleElm < key && numArray.length > 1){
      return binarySearch(numArray.splice(middleIndex, numArray.length), key)
   } else if {
      return binarySearch(numArray.splice(0, middleIndex), key)
   } else return false 
}
Enter fullscreen mode Exit fullscreen mode

So, in this piece of code, we define two variables middleIndex to store the middle Index of the array and middleElem to store the middle element of the array. Simple?

Next, we go ahead and write out the base case which checks if the middle element is the same as our key and returns true ending our function since we have already located it.

We again write another "if" statement for our recursion which checks if the middle number is less than the key and also if the numbers array is greater than one. If the key is greater than the middle number, we splice the array and remain with the section above the middle number.

The splice function takes in two arguments, the index from the point you want to start slicing the array and the index where you want to end. it returns the sliced part.

Then we call the function recursively to repeat this process until the base case is reached hence completing our function.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay