为什么我的算法不能在我的数组中找到索引?

时间:2018-06-15 00:27:46

标签: javascript binary-search khan-academy

为什么我的算法返回“-1”意味着目标值73不在数组中? (当显然73在阵列中时)。 [这是来自可汗学院,但没有帮助]

它应该返回数组中位置的索引, 如果数组不包含targetValue

,则返回“-1”
Var doSearch = function(array, targetValue) {
    var min = 0;
    var max = array.length - 1;
    var guess;
    while(max >= min) {
        guess = floor((max*1 + min*1) / 2);
        if (guess === targetValue) {
            return guess;
        } else if (guess < targetValue) {
            min = guess + 1;
        } else {
            max = guess - 1;
        }
    }
    return -1;
};

var 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];

var result = doSearch(primes, 73);
println("Found prime at index " + result);

2 个答案:

答案 0 :(得分:4)

您已将guess设置为数组索引,但之后您将其与targetValue进行比较。您需要比较该索引处的数组元素。

&#13;
&#13;
var doSearch = function(array, targetValue) {
  var min = 0;
  var max = array.length - 1;
  var guess;
  var guessvalue;
  while (max >= min) {
    guess = Math.floor((max * 1 + min * 1) / 2);
    guessValue = array[guess];
    if (guessValue === targetValue) {
      return guess;
    } else if (guessValue < targetValue) {
      min = guess + 1;
    } else {
      max = guess - 1;
    }
  }
  return -1;
};

var 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
];

var result = doSearch(primes, 73);
console.log("Found prime at index " + result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的函数doSearch()无法将array的任何值与targetValue进行比较。您需要访问guess位置并进行比较,如下所示:

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

var 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];

var result = doSearch(primes, 73);
console.log("Found prime at index " + result);
&#13;
&#13;
&#13;

  

警告:   函数floor()在JavaScript中不存在。您应该使用Math.floor()。此外,函数println()。请改用console.log()