javascript - 您的所有断言都通过了吗?

标签 javascript arrays assert

这是我在 javascript 中编写二进制搜索代码时得到的语句。 我不知道错误是什么如果有人能解决这个问题。

        var doSearch = function(array, targetValue) {
        var min = 0;
    var max = array.length - 1;
    var guess;
    while(min <= max)
    {
        guess = Math.floor((min+max)/2);
        if(array[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);

Program.assertEqual(doSearch(primes, 73), 20);//我在这一行出错,我不知道是怎么回事,因为返回索引 20 并与 20 进行比较,但它仍然很糟糕!!!

最佳答案

您需要检查值,而不是针对 targetValue 的索引

} else if (array[guess] < targetValue) {
//         ^^^^^^^^^^^^

var doSearch = function(array, targetValue) {
    var min = 0,
        max = array.length - 1,
        guess;

    while (min <= max) {
        guess = Math.floor((min + max) / 2);
        if (array[guess] === targetValue) {
            return guess;
        }
        // no need for else, because return terminates the function
        if (array[guess] < targetValue) { // use the item, not the index
            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
];

console.log(doSearch(primes, 73));

关于javascript - 您的所有断言都通过了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631931/

相关文章:

javascript - 单击子级别的垂直 CSS 和 Javascript onclick 菜单使其消失

javascript - 使用纯 JavaScript 加载外部 JSON 数据

python 错误 - numpy 数组上的移动平均值

cuda - 是否可以从 CUDA 内核中获取断言信息?

javascript - a-google-place 自动完成选择的回调

javascript - 在 Enter 上添加 br 标签

c# - C# 中的监视器数组

java - Java中的二维数组打印格式

.net - Debug.Assert(false) 不会在 win8 Metro 应用程序中触发

c++ - 一行断言测试 STL 容器是否已排序