此代码块可完美运行。这是用javascript编写的二进制搜索算法。我是从网站上收集的。
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
var result = binarySearch([2,3,4,5,6,7,8,9,10],2);
console.log(result);
但是,如果我以这种方式更改while循环内的代码,它将无法正常工作。 我已经尝试了几次,但无济于事。请帮我。有什么问题吗?
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
// Look here. Here is my problem
if(arr[mid] > target){
right = mid - 1;
}
}
return -1;
}
var result = binarySearch([2,3,4,5,6,7,8,9,10],2);
console.log(result);
答案 0 :(得分:0)
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
if(arr[mid] > target){
right = mid - 1;
}
和
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
在这种情况下是等效的。