class ArrayTest3 //折半查找
{
public static void main(String[] args)
{
int[] arr=new int[]{1,3,4,6,7,9};
int x=haflSearch(arr,7);
System.out.println("x="+x);
}
public static int haflSearch(int[] arr,int dey)//定义的一个函数用来查找
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=(min+max)/2;
while(dey!=arr[mid])
{
if(dey>arr[mid])
min=mid+1;
else if(dey<arr[mid])
max=mid-1;
if(min>max)
return -1;
mid=(max+min)/2;
}
return min;
}
}
|