二分查詢成長錄

wangxiaojin發表於2018-08-22

A是一個已排序的陣列,x是目標值。 如果找到目標值,返回目標值在陣列中的序號。如果沒有找到目標值,返回目標值應該被插入的位置

 function bSearch(ary,x){
     let l=0,r=ary.length-1,guess;
     if(x<0){
       return 0
     }
     if(x>ary[ary.length-1]){
        return ary.length
     }
     while(l<=r){
        guess=Math.floor((l+r)/2);
        if(ary[guess]==x) return guess;
        if(guess+1<=ary.length-1){
          if(ary[guess]<x&&ary[guess+1]>x){
            return guess+1
          }
        }
        if(guess-1>=0){
          if(ary[guess]>x&&ary[guess-1]<x){ 
             return guess;
          }
        }
        
        if(ary[guess]<x){
             l=guess+1
        }else if(ary[guess]>x){
             r=guess-1;
        }
     }
  }
  
   let  A=[3,5,7,13,22,25];
   console.log(bSearch(A,30));

複製程式碼
function bSearch(ary,x){
     let l=0,r=ary.length-1,guess;
     if(x<0){
       return 0
     }
     if(x>ary[ary.length-1]){
        return ary.length
     }
     while(l<=r){
        guess=Math.floor((l+r)/2);
        if(ary[guess]==x) return guess;
        if(guess+1<=ary.length-1){
          if(ary[guess]<x&&ary[guess+1]>x){
            return guess+1
          }
        }
        if(guess-1>=0){
          if(ary[guess]>x&&ary[guess-1]<x){ 
             return guess;
          }
        }
        
        if(ary[guess]<x){
             l=guess+1
        }else if(ary[guess]>x){
             r=guess-1;
        }
     }
  }
  
   let  A=[3,5,7,13,22,25];
   console.log(bSearch(A,30));



複製程式碼

簡化版:

function bSearch(ary,x){
  let l=0,r=ary.length-1,guess;
  while(l<=r){
     guess=Math.floor((l+r)/2);
     if(ary[guess]==x) return guess;
     if(ary[guess]<x){
        if(guess==ary.length-1||ary[guess+1]>x){
            return guess+1
        }
        l=guess+1
     }else if(ary[guess]>x){
        if(guess==0||ary[guess-1]<x){
          return guess;
        }
        r=guess-1;
     }
  }
}



複製程式碼

相關文章