- class halfSearch
- {
- public static void main(String[] args)
- {
- int []arr={1,2,3,4,5,6};
- int index=halfSearch(arr,5);
- System.out.println("index="+index);
- }
- public static int halfSearch(int [] arr,int key)
- {
- int min=0,max=arr.length-1,mid;
-
- mid=(min+max)/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=(max+min)/2;
- }
- return mid;
- }
- }
复制代码 |