美文网首页
js二分查找

js二分查找

作者: Bookish倩宝 | 来源:发表于2016-09-29 23:39 被阅读0次

    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

    相关文章

      网友评论

          本文标题:js二分查找

          本文链接:https://www.haomeiwen.com/subject/erelyttx.html