我試圖在JavaScript中實現二進制搜索,我完全是新的JS。我大多習慣於C++語法,所以對我來說打破我的習慣有點困難。JavaScript新手上路有人可以幫我調試我的程序嗎?
當我將此腳本包含在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;
}
調試將使用Chrome調試器。在Chrome中打開你的html文件並按下「Ctrl」+「Shitf」+「J」。然後,您可以在腳本中添加斷點,並查看可能出現的問題。 – qelper
我也推薦JSFiddle http://jsfiddle.net/進行調試 – Jazzepi