Rajkumar Somasundaram
Rajkumar Somasundaram

Reputation: 1270

Returning the value out of a binary search function

The following code does Binary search of an array. I did the hard part and got the code to work in theory; Unfortunately, I am having trouble returning the value out of the function;

In short, I want 'len' to be returned ; If you set a breakpoint in that line you will see that 'len' contains the right answer. But I am missing something very silly. Please help me identify.

var states = ['Alabama','Alaska','American Samoa','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Federated States of Micronesia','Florida','Georgia','Guam','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Marshall Islands','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Northern Mariana Islands','Ohio','Oklahoma','Oregon','Palau','Pennsylvania','Puerto Rico','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virgin Island','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
function binarySearch(arr1,term){
  var arr = [...arr1],
    len = 0;
  function helper(arr,term) {
    if(arr.length > 1) {
      if(arr[Math.floor(arr.length/2)] === term) {
          len += Math.floor(arr.length/2);
          return len;
      }
      if(arr[Math.floor(arr.length/2)] < term) {
          len += Math.floor(arr.length/2);
          arr.splice(0,Math.floor(arr.length/2));
          helper(arr,term)
      }
      else if (arr[Math.floor(arr.length/2)] > term) {
          arr.splice(Math.floor(arr.length/2),arr.length-1);
          helper(arr,term)
      }
    } else {
        return 'Element not found';
    }
  }
  return helper(arr,term);
}
console.log(binarySearch(states,"Arizona"));

Upvotes: 0

Views: 35

Answers (1)

trincot
trincot

Reputation: 350147

Your recursive call should also be returned to the caller:

Replace:

helper(arr,term)

with:

return helper(arr,term)

at both instances.

Upvotes: 1

Related Questions