1. 程式人生 > >JAVA:實現二分查詢

JAVA:實現二分查詢

應用 while迴圈
public static int search(int[]arr,int num){
    int lower=0,upper=arr.length;
    int mid=0;
    while (arr[mid]!=num){
        mid=(lower+upper)/2;
        if(num>arr[mid]){
            lower=mid+1;
        }
        else{
            upper=mid-1;
        } 
    }
    return mid;
public  static void main(String[] args){
   int[]arr={1,2,3,4,5,6,7,8,9};
   
   int pos=search(arr,5);
   System.out.println(pos);

}