我正在尝试实现二进制搜索
,我做了以下事情:
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
。我做错了什么?
最佳答案
尝试改变:
return bs([...a].slice(mpoint,a.length), x)
到:
return bs([...a].slice(mpoint,a.length), x) + mpoint
关于javascript - 没有得到正确的二进制搜索算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56631854/