class ArrayTest3
{
public static void main(String[] args)
{
int[] arr= {3,4,5,6,7,8,9};
int index=halfSerch(arr,10);
System.out.println("index="+index);
}
/*
折半查找:效率提高,但是数组要有序排列。
原理:两数取中间,
*/
public static int halfSerch(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length;
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 = (min+max)/2;
}
return mid;
}
如过key是10 那么为什么 输出的不是-1?而是:
D:\javadm\day04>java ArrayTest3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayTest3.halfSerch(ArrayTest3.java:21)
at ArrayTest3.main(ArrayTest3.java:7)
|
|