【发布时间】: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