二进制搜索代码 [英] Binary Search Code

查看:91
本文介绍了二进制搜索代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为二进制搜索算法编写自己的函数,但似乎找不到逻辑上的差异.每当我搜索4时,它都不会返回理想的响应.

I am coding my own function for a binary search algorithm and I can't seem to find the discrepancies in logic. When ever I search for 4 it does not return the ideal response.

下面的代码:

var list = [1,2,3,4,6,7,13,18,19];

function binarySearch(list,number) {
    var newList = list;
    while (newList.length >= 1) {
        var halfNum = Math.round(newList.length/2);
            if (newList[halfNum] === number) {
            return "Number Found";
        } else if (newList[halfNum] < number) {
            newList = newList.slice(halfNum + 1,newList.length - 1);
        } else {
            newList = newList.slice(0,halfNum - 1);
        }
    }
}


console.log(binarySearch(list,4));

推荐答案

此处的问题是您执行的范围错误. javascript slice函数将数组切成[start,finish)间隔,这意味着它在新数组中不包含end索引

The problem here is that you are doing the ranges wrong. the javascript slice function cuts the array into the interval [start,finish), and by that I mean that it does not include the end index in the new array

所以你应该改变这个:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length - 1);
    } else {
        newList = newList.slice(0,halfNum - 1);
    }

对此:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length);
    } else {
        newList = newList.slice(0,halfNum);
    }

这篇关于二进制搜索代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆