class Test1
{
public static void main(String[] args)
{
int[] arr={1,2,3,4,5,6,7,8,9,12};
int key=8;
int n= halfSearch(arr,key);
int m=halfSearch_1(arr,key);
System.out.println("毕向东老师的代码结果"+n);
System.out.println("减1后的结果"+m);
}
public static int halfSearch(int[] arr,int key)
{
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 = (max+min)/2;
}
return mid;
}
//修改后的折半查找函数
public static int halfSearch_1(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length-1;
mid = (max+min)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min = mid; //把min=mid+1改为min=mid
else if(key<arr[mid])
max = mid; //把min=mid-1改为max=mid
if(min>max)
return -1;
mid = (max+min)/2;
}
return mid;
}
} |