仅当列表是有序的时候,二分查找才管用。
非递归
public class Test{
public static int binary_search(int []arr,int key) {
int low=0;
int high=arr.length-1;
while(low<=high) {
int mid=(low+high)/2;
if(arr[mid]==key) {
return mid;
}
else if(arr[mid]<key) {
low=mid+1;
}
else {
high=mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int []arr1= {1,2,3,4,5,6,7};
System.out.println(binary_search(arr1,7));
}
}
输出:6
递归
public class Test {
public static int binary_search(int[] arr,int low,int high,int key) {
if(arr==null||arr.length==0||low>high)
return -1;
int mid=(low+high)>>1;
if(arr[mid]==key) {
return mid;
}else if(arr[mid]>key) {
return binary_search(arr,low,mid-1,key);
}else {
return binary_search(arr,low+1,high,key);
}
}
public static void main(String[] args) {
int []arr= {1,2,3,4,5,6,7};
System.out.println(binary_search(arr,0,arr.length-1,3));
}
}
输出:2