我正在尝试在 javascript 中实现二进制搜索,而我对 JS 完全陌生。我主要习惯于 C++ 语法,所以要打破我的任何习惯对我来说有点困难。
当我将此脚本包含在 html 文档中时,如果数组大小小于 1,它将无法退出脚本,并且如果我输入无序数组,则不会触发数组顺序警报。另外,程序似乎永远不会完成while循环,所以不知道是否还有其他问题。
任何帮助,将不胜感激!
var size = parseInt(prompt("Enter the size of the array:"));
if(size < 1) {
alert("ERROR: you entered an incorrect value for the array size!");
return;
}
var arr = [size];
var input = parseInt(prompt("Enter the numbers in the array in increasing order,"
+ " separated by a space, and press enter:"));
arr = input.split(" ");
var checkOrder = function(array) {
for(var i = 0; i < size-1; i++) {
if(array[i] > array[i+1]) {
return false;
}
}
return true;
}
if(!checkOrder(arr)) {
alert("The values entered for the array are not in increasing order!");
}
var search = parseInt(prompt("Enter a number to search for in the array: "));
var lp = 0; //left endpoint
var rp = size; //right endpoint
var mid = 0;
var counter = 0;
var found = false;
while(lp <= rp) {
mid = Math.floor((lp + rp)/2);
if(arr[mid] == search) {
alert("Found value " + search + " at index " + mid);
counter++;
found = true;
break;
} else if(arr[mid] > search) {
rp = mid + 1;
counter++;
} else {
lp = mid;
counter++;
}
}
if(!found) {
alert("The value " + search + "was not found in the array");
alert("I wasted " + counter + " checks looking for a value that's not in the array!");
return;
}