Skip to content
Advertisement

How to create a binary search with recursion

I am attempting to write a “binary search” which I’ve never done before. The code below does not work when the value searched for is 6 or 2 and I want to know what I am doing wrong and how to remedy it.

EDIT

To explain what it is suppose to do (based on my understanding) a binary search requires that an array is already sorted, it then looks for the mid-point index of an array. For example, if an array had nine indexes (0-8)the the mid point would be index 4.

JavaScript

The algorithm then determines if that mid point has a higher or lower value than the number you are searching for. All elements on the side of the array that does not contain the searched for number and that exist before the midpoint value simply get removed. If the search for value is 8 then the result would be:

JavaScript

Code

JavaScript

Advertisement

Answer

  1. You are slicing it wrong.

Use this code:

JavaScript
  1. Also, if the search element is not in array, this will go on infinitely. Add a base case for that too.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement