1. 程式人生 > >Java版二分查詢

Java版二分查詢

簡介

  • Java版陣列二分查詢實現
public class BinaryFind {
    public static void main(String[] args){
        int[] arr=new int[]{5,3,6,7,9,8,4,2,1};
        Arrays.sort(arr);
        int index=getIndex(arr,5);
        System.out.println(index);
    }

    //二分查詢
    public static int getIndex(int[] arr,int element){
        if(arr==null||arr.length<=0){
            return -1;
        }
        int min=0;
        int max=arr.length-1;
        int mid=(max+min)/2;
        while(min<=max){
            if(arr[mid]==element){
                return mid;
            }
            if(arr[mid]>element){
                max=mid-1;
            }
            if(arr[mid]<element){
                min=mid+1;
            }
            mid=(max+min)/2;
        }
        return -1;
    }
}