javascript - 为什么我的 javascript 显示值未建立?

标签 javascript arrays binary-search

我正在尝试在数组中进行二分搜索,但即使我在提示输入中输入了数组中的数字,我的 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 显示值未建立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670271/

相关文章:

javascript - 我可以关闭 create-react-app 分块机制吗?

javascript - 比较两个数组和唯一值计数?

android - 滚动列表时显示字母预览

c - C 中的二分查找 - 当整数不在数组中时错误的退出代码

c++ - 二进制搜索以在 STL C++ 多重集中查找小于或等于的值

algorithm - 二分查找和不变关系

javascript - jQuery promise 不使用方法 html undefined

确认脚本中的 Javascript IIF

javascript - 我如何修改此 e.preventDefault 以在除主页之外的所有页面上工作?

javascript - 如果对象值在数组中是唯一的,则执行此操作