我正在尝试实现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
。我在做什么错?
答案 0 :(得分:4)
尝试更改:
return bs([...a].slice(mpoint,a.length), x)
收件人:
return bs([...a].slice(mpoint,a.length), x) + mpoint