二分查找-binarySearch

二分查找

const binarySearch=(list,left,right,key)=>{
    const mid=Math.floor((left+right)/2)
    if(list[mid]==key)return mid
    if(list[mid]<key)return binarySearch(list,mid+1,right,key)
    if(list[mid]>key)return binarySearch(list,left,mid-1,key)
    return -1
}
const list=[1,2,3,4,5,6,7,8,9]
console.log(binarySearch(list,0,list.length-1,7))

 

posted @ 2019-03-19 13:46  朱现国  阅读(138)  评论(0编辑  收藏  举报