我正在尝试在数组中进行二进制搜索,但即使我在提示输入中输入数组中的数字,我的 javascript 也没有显示任何值
var array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100, 102, 105, 200, 250, 300, 320, 350];
var search = parseInt(prompt("enter what you search for"));
var first = 0,
last = array.length - 1,
position = 0,
middle, flag = false;
while ((flag == false) && (first <= last)) {
middle = ((first + last) / 2);
if (array[middle] == search) {
flag = true;
position = middle;
} else
if (array[middle] > search)
last = middle - 1;
else
first = middle + 1;
}
if (flag)
document.write("</br>value founded in position " + position);
else
document.write("</br>value not founded ");
最佳答案
middle value calculation.
middle = Math.round(first + ((last - first) / 2));
//你的代码..
var array =[10,20,30,40,50,60,70,80,90,95,100,102,105,200,250,300,320,350] ;
var search= 20; //parseInt(prompt ("enter what you search for"));
var first=0, last=array.length-1,
position=0,
middle ,
flag=false;
while((flag==false) && (first <=last)) {
middle = Math.round(first + ((last - first) / 2)); //((first+last)/2); low + (last - low)/2
if (array[middle]==search){
flag=true;
position=middle ;
}else if(array[middle]>search) {
last=middle-1 ;
}
else {
first= middle+1;
}
}
if (flag)
document.write ("</br>value founded in position "+position);
else
document.write("</br>value not founded ");
关于javascript - 为什么我的 javascript 显示值(value)不成立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670271/