js 二分查找的实现

页面导航:首页 > 网络编程 > JavaScript > js 二分查找的实现

js 二分查找的实现

来源: 作者: 时间:2016-02-05 11:06 【

1 递归实现function binarySearch(data, dest, start, end){ var end = end || data length - 1, start = start || 0, m = Math floor((start +

1.递归实现

function binarySearch(data, dest, start, end){
    var end = end || data.length - 1,
        start = start || 0,
        m = Math.floor((start + end) / 2);
    if(data[m] == dest){
        return m;
    }
    if(dest < data[m]){
        return binarySearch(data, dest, 0, m-1);
    }else{
        return binarySearch(data, dest, m+1, end);
    }
  
    return false;
}
var arr = [-34, 1, 3, 4, 5, 8, 34, 45, 65, 87];
binarySearch(arr,4);
//3

2.非递归实现

function binarySearch(data, dest){
    var h = data.length - 1,
        l = 0;
    while(l <= h){
        var m = Math.floor((h + l) / 2);
        if(data[m] == dest){
            return m;
        }
        if(dest > data[m]){
            l = m + 1;
        }else{
            h = m - 1;
        }
    }
  
    return false;
}
var arr = [-34, 1, 3, 4, 5, 8, 34, 45, 65, 87];
binarySearch(arr,4);
//3






Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<