js 二分查詢的實現
阿新 • • 發佈:2018-12-16
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
---------------------
作者:天晟
來源:CSDN
原文:https://blog.csdn.net/a324539017/article/details/41801499
版權宣告:本文為博主原創文章,轉載請附上博文連結!