/*
数组的查找操作。
折半查找
*/
class ArrayTest4
{
public static void main(String[] args)
{
int[] arr = {2,4,5,7,8,19,32,45};
int index=find(arr, 45);
System.out.print("index="+index);
}
public static int find(int[] arr,int key)
{
int min=0, max=arr.length-1, mid;
while (min<=max)//这里为什么要min<=max,写成min<max,运行结果就是-1?
{
mid=(min+max)/2;
if(key>arr[mid])
min = mid+1;
else if(key<arr[mid])
max =mid-1;
else
return mid;
}
return -1;
}
}
|
|