【问题标题】:Binary Search Code二进制搜索码
【发布时间】:2014-03-22 06:53:48
【问题描述】:

我正在为二进制搜索算法编写自己的函数,但我似乎无法找到逻辑上的差异。当我搜索 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));

【问题讨论】:

  • 作为一种通用调试技术,将console.log 调用插入代码的关键部分以显示计算值。这将显示哪里出了问题。
  • @Matt 谢谢,我试过了,但我无法弄清楚代码的错误所在。
  • 一个好的开始是在 slice 之后查看 newList

标签: javascript binary-search


【解决方案1】:

这里的问题是你做错了范围。 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);
    }

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多