public class demo08 {
public static void main(String[] args) {
int[] arr = {10,15,20,30,35,50};
int index = searchHalf(arr,20);
System.out.println("元素所在的索引值是:" + index);
}
public static int searchHalf(int[] arr,int target){
int max = arr.length-1;
int min = 0;
int mid = (max+min)/2;
while(true){
if(target<arr[mid]){
max = mid - 1;
}else if(target>arr[mid]){
min = mid + 1;
}else{
return mid;
}
if(max<min){
return -1;
}
mid = (max+min)/2;
}
}
}
|
|