- class HalfSearch
- {
- public static void main(String[] args)
- {
- int [] arr ={12,23,25,34,56,67,78,80};
- int index= halfSearch(arr,56);
- System.out.println("index="+index);
- }
- public static int halfSearch(int[] arr,int key)
- { int min=0;
- int max=arr.length-1;
- int mid=0;
- while (min<=max)
- {
- mid=(mid+max)/2;
- if ( key==arr[mid])
- {
- return mid;
- }
- else if (key>arr[mid])
- {
- min=mid+1;
- }
- else if (key<arr[mid])
- {
- max=mid-1;
- }
-
- }
- return -1;
- }
- }
- 查找56(角标为4),运行结果为:index=4
复制代码 |