在javascript中实现二进制搜索

时间:2016-10-23 07:57:45

标签: javascript binary-search

我正在尝试在javascript中实现二进制搜索。我不知道我的脚本出了什么问题。每当我点击搜索按钮时,页面都会无响应。谢谢。

var i,print,arr;
	arr = [1,2,3,4,5,6,7,8,9,10];
	print = document.getElementById("showArray");
	for(i = 0; i < arr.length; i++){
	 print.innerHTML += arr[i] + "&nbsp;"; 
	}
	function binarySearch(searchValue){ 
	  var lowerIndex, higherIndex, middleIndex,writeResult;
	  lowerIndex = 0;
	  higherIndex = arr.length;
	  writeResult = document.getElementById("showResult");
	  while(lowerIndex <= higherIndex){
	    middleIndex = (higherIndex + lowerIndex) / 2;
		if(searchValue == arr[middleIndex]){
		  writeResult.innerHTML = "PRESENT";
		  consol.log('Present');
		  break;
		}
		else if(searchValue > arr[middleIndex]){
		  lowerIndex = middleIndex + 1;
		}
		else if(searchValue < arr[middleIndex]){
		  higherIndex = middleIndex - 1;
		}
	  }
	}
<button onclick = "binarySearch(1)">SEARCH</button>
	<p id = "showArray" style = "font-size: 40px; padding:0px;">       </p>
	<p id = "showResult">Result is:</p>

3 个答案:

答案 0 :(得分:0)

尝试类似

的内容
<textarea name="question" disabled cols="80%" rows="10">
     <?echo $results['question']?>
</textarea>

答案 1 :(得分:0)

主要问题是,您没有使用middleIndex计算的整数部分。这使得无法检查数组的给定索引处的值,因为索引必须是整数。

var i,
    print = document.getElementById("showArray"),
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (i = 0; i < arr.length; i++) {
    print.innerHTML += arr[i] + "&nbsp;";
}

function binarySearch(searchValue) {
    var lowerIndex = 0,
        higherIndex = arr.length - 1,
        middleIndex,
        writeResult = document.getElementById("showResult");

    while (lowerIndex <= higherIndex) {
        middleIndex = Math.floor((higherIndex + lowerIndex) / 2);
        if (searchValue == arr[middleIndex]) {
            writeResult.innerHTML = "PRESENT " + middleIndex;
            break;
        }
        if (searchValue > arr[middleIndex]) {
            lowerIndex = middleIndex + 1;
        } else {
            higherIndex = middleIndex - 1;
        }
    }
}
<button onclick="binarySearch(2)">SEARCH</button>
<p id="showArray" style="font-size: 40px; padding:0px;">       </p>
<p id="showResult">Result is:</p>

答案 2 :(得分:0)

没有break的二进制搜索的迭代示例。

运行时间:log2(n)

&#13;
&#13;
function search(array, target) {
  let min = array[0]
  let max = array.length - 1;
  let guess;
  
  while (max >= min) {
    guess = Math.floor((min+max)/2);
    if (array[guess] === target) {
      return guess;
    } else if (array[guess] > target) {
      max = guess - 1;
    } else {
      min = guess + 1;
    }
  }

  return -1;
}

const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
console.log(search(primes, 67));
&#13;
&#13;
&#13;