- class HalfSearch
- {
- public static void main(String[] args)
- {
- //折半查找
- int arr[]={5,1,6,4,2,8,9};
- int index=halfSearch(arr,2);
- System.out.println("2所在位置下角标为:"+index);
- }
- //折半查找,效率高,但是必须保证数组为有序数组
- public static int halfSearch(int[] arr,int key)
- {
- //int min=0,max=arr.length-1,mid=(max+min)/2;
- int min,max,mid;
- min=0;
- max=arr.length-1;
- mid=(max+min)/2;
- while(arr[mid]!=key)
- {
- if(key>arr[mid])
- min=mid+1;
- else if(key<arr[mid])
- max=mid-1;
- if(min>max)
- return -1;
- mid=(mid+max)/2;
- }
- return mid;
- }
- }
复制代码 |