我在Chrome控制台中尝试过二进制搜索。但是当我运行代码时,整个Chrome被绞死了,我不得不杀死这些页面:
var arr = [1, 3, 5, 8];
var binary = function (arr, search) {
var low = 0;
var high = arr.length - 1;
var mid = (high + low) / 2;
while (low <= high) {
if (search === arr[mid]) {
return mid;
} else if (search > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
};
console.log(binary(arr, 3));
答案 0 :(得分:4)
问题出在这一行
var mid = (high + low) / 2;
由于mid
是浮点值,arr[mid]
始终返回undefined
。您可以像这样确认这个
var arr = [1, 3, 5, 8];
console.log(arr[1.5]);
// undefined
<强>解决方案强>
要解决此问题,您可以将其转换为整数,例如
var mid = parseInt((high + low) / 2, 10);
正如Rick在评论中所指出的,mid
计算必须在while
循环中进行。因此,while
循环看起来像这样
while (low <= high) {
mid = parseInt((high + low) / 2, 10);
if (search === arr[mid]) {
return mid;
} else if (search > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
答案 1 :(得分:1)
在您的代码中,mid
总是 1.5,因为它是在循环之前计算的。
相反,在循环中移动mid
计算,并将其计算为high
和low
的舍入平均值:
var arr = [1, 3, 5, 8];
var binary = function(arr, search) {
var low = 0;
var high = arr.length - 1;
var mid;
while (low <= high) {
mid = Math.round((high + low) / 2);
if (search === arr[mid]) {
return mid;
} else if (search > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
};
console.log(binary(arr, 3)); //1
console.log(binary(arr, 8)); //3
console.log(binary(arr, 17)); //-1