【问题标题】:Not getting the binary search algorithm correct没有得到正确的二分搜索算法
【发布时间】:2019-10-31 01:54:23
【问题描述】:

我正在尝试实现binary search,我做了以下操作:

function bs(a,x) {
    // a : array to look into
    // x : number to find
    let mpoint = Math.floor(a.length / 2);
    if(x >= a[mpoint]) {
        if(x == a[mpoint]) { return mpoint;}
        else {
            return bs([...a].slice(mpoint,a.length), x)
        }
    }else {
        if(x == a[mpoint]) {return mpoint;}
        else {
            return bs([...a].slice(0,mpoint),x)
        }
    }
}


bs([ 2, 3, 4, 10, 40 ], 10)

但结果我得到了一个不正确的index。我做错了什么?

【问题讨论】:

  • else 中的 if 没有意义,因为在该部分中 x 不可能相等。
  • 索引是正确的,但显然它是切片数组的。所以添加mpoint
  • [...a] 扩展字面量是多余的,slice 无论如何都会创建一个新数组

标签: javascript algorithm search binary-search


【解决方案1】:

尝试改变:

return bs([...a].slice(mpoint,a.length), x)

到:

return bs([...a].slice(mpoint,a.length), x) + mpoint

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2017-07-02
    • 2013-04-23
    相关资源
    最近更新 更多