class ArrayTest6{
public static void main(String[] args){
//int[] arr=new int[]{5,1,6,4,2,8,9};
int[] arr=new int[]{1,2,3,5,6,8,16};
//int index=getIndex(arr,6);
int index=halfSearch(arr,11);
System.out.println(index);
}
/*
折半查找,要求数组是有序的
*/
public static int halfSearch(int[] arr,int value){
int min=0,max=arr.length-1,mid=(min+max)/2;
while(arr[mid]!=value){
if(value==arr[mid]){
return mid;
}
else if(value<arr[mid]){
max=mid-1;
}
else if(value>arr[mid]){
min=mid+1;
}
if(min>max){
return -1;
}
mid=(min+max)/2;
}
}
}
|
|