二进制搜索代码

时间:2014-02-21 00:45:22

标签: javascript binary-search

我正在为二进制搜索算法编写自己的函数,我似乎无法找到逻辑上的差异。当我搜索4时,它不会返回理想的响应。

以下代码:

var list = [1,2,3,4,6,7,13,18,19];

function binarySearch(list,number) {
    var newList = list;
    while (newList.length >= 1) {
        var halfNum = Math.round(newList.length/2);
            if (newList[halfNum] === number) {
            return "Number Found";
        } else if (newList[halfNum] < number) {
            newList = newList.slice(halfNum + 1,newList.length - 1);
        } else {
            newList = newList.slice(0,halfNum - 1);
        }
    }
}


console.log(binarySearch(list,4));

1 个答案:

答案 0 :(得分:2)

这里的问题是你做的范围错了。 javascript slice函数将数组切换到[start,finish]区间,并且我的意思是它不包括新数组中的结束索引

所以你应该改变这个:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length - 1);
    } else {
        newList = newList.slice(0,halfNum - 1);
    }

对此:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length);
    } else {
        newList = newList.slice(0,halfNum);
    }