直接上码了注释写得很详细:
function bsearch(A,x){ //l:查找范围左 r:查找范围右 let l = 0, //查询范围左边界 r = A.length-1, //查找范围右边界 guess //中间猜测位置 while(l <= r){ //guess等于l,r中间位置 guess = Math.floor( (l+r)/2 ) //判断当前位置是否为要查找的值,是则返回下标 if(A[guess] === x) return guess //如果当前位置值大于要查询的值 右边界位置减一 else if(A[guess] > x) r = guess -1 //否则左边界位置加1 else l = guess + 1 } //找不到返回-1 return -1 } const a = [3,5,4,7,12,42,47,66,71,78]; console.log(bsearch(a,12))//4 console.log(bsearch(a,4))//-1 console.log(bsearch(a,66))//7 console.log(bsearch(a,5))//1
原文地址:https://www.cnblogs.com/y-y-y-y/p/10241997.html
时间: 2024-10-03 22:54:01