二分搜索法

public   class  Search {

    
/**
     * 前提条件array数组已排序
     
*/
    
public   static   boolean  binarySearch( int [] array,  int  target) {
        
boolean  result  =   false ;
        
int  bottom  =   0 ;
        
int  top  =  array.length - 1 ;
        
while  (bottom  <=  top) {
            
int  mid  =  (top  +  bottom)  /   2 ;
            
if  (target  ==  array[mid]) {
                result 
=   true ;
                
break ;
            } 
else   if  (target  <  array[mid]) {
                top 
=  mid  -   1 ;
            } 
else   if  (target  >  array[mid]) {
                bottom 
=  mid  +   1 ;
            }
        }

        
return  result;
    }

    
public   static   void  main(String[] args) {
        
int  [] array  =  { 1 , 3 , 5 , 7 , 9 , 10 };
        
boolean  result  =  binarySearch(array,  10 );
        System.out.println(result);
    }
}

你可能感兴趣的:(二分搜索法)