Binary search recursive function returning undefined in JavaScript? -


hi, getting undefined following javascript code. tool debugging javascript, webstorm best?

//input var inputarray = [1, 2, 3, 4, 5, 5, 5, 6, 66]; var searchvalue = 2; //output var arraylength = inputarray.length; var arraycurrent = inputarray; var currentindex = arraylength; function binarysearch() {     currentindex = math.floor(arraycurrent.length / 2);     if (searchvalue == arraycurrent[currentindex]) {         var x=currentindex;         return x;     } else if (searchvalue > arraycurrent[currentindex]) {         arraycurrent = arraycurrent.slice(currentindex + 1);         binarysearch();//recursive call      } else if (searchvalue < arraycurrent[currentindex]) {         arraycurrent = arraycurrent.slice(0, currentindex - 1);         binarysearch();//recursive call     }  } var found=binarysearch(); console.log("the index of searched value is: " + found); 

console output: index of searched value is: undefined  

the recursion happens if function calls itself. in case, can use loop.

i found following example on oliver caldwell's blog :

var inputarray = [1, 2, 3, 4, 5, 5, 5, 6, 66];  var searchvalue = 6;    function binarysearch(searchvalue, inputarray) {      var minindex = 0,          maxindex = inputarray.length - 1,          currentindex,          currentelement;         while (minindex <= maxindex) {          currentindex = (minindex + maxindex) / 2 | 0;          currentelement = inputarray[currentindex];             if (currentelement < searchvalue)              minindex = currentindex + 1;          else if (currentelement > searchvalue)              maxindex = currentindex - 1;          else              return currentindex;      }         return -1;  }    var found = binarysearch(searchvalue, inputarray);  console.log("the index of searched value is: " + found);


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -