二进制搜索递归函数在JavaScript中返回undefined?

Pet*_*nov -4 javascript undefined binary-search

嗨,我从以下JavaScript代码中获取未定义.我想要一个调试JavaScript的工具,Webstorm是最好的吗?

//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 the searched value is: " + found);
Run Code Online (Sandbox Code Playgroud)
Console output:
the index of the searched value is: undefined 
Run Code Online (Sandbox Code Playgroud)

ble*_*lex 5

只有在函数调用自身时才会发生递归.但在这种情况下,您可以使用循环.

我在Oliver Caldwell的博客上找到了以下示例:

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 the searched value is: " + found);
Run Code Online (Sandbox Code Playgroud)

  • 现在[尝试用`searchValue = 3`请](http://jsfiddle.net/ZLAsW/2/)...数组的切片是_wrong_,因为第二个参数是"[z]基于ero的索引在哪个结束提取.__slice提取但不包括end .__"(引自[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice),由我突出显示) - 它必须是第二个else-if分支中的`arrayCurrent.slice(0,currentIndex)`.固定 - > http://jsfiddle.net/ZLAsW/3/ (2认同)
  • _"我会删除我的"然后"_ - 你不敢!:-)你的答案是正确的,除了那个小故障(并且只是从原始代码转移) - 递归函数调用的缺失返回是这里的主要问题.为什么不在你的答案中编辑那个小东西(也许更新小提琴的链接)......并且信用是你的全部;-) (2认同)