二分查找时间复杂度为:log2n
package leecode;
public class BinarySearch {
//二分法普通方法
public static int binSearch_1(int key, int[] arr) {
int low = 0;
int high = arr.length-1;
if(key<arr[low]||key>arr[high]||low>high){
return -1;
}
while (low<=high){
int mid = (low+high)/2;
if (key==arr[mid]){
return mid;
}else if(key<arr[mid]){
high = mid-1;
}else {
low = mid + 1;
}
}
return -1;
}
// 二分法(递归一)
public static int binSearch_2(int key,int[] array,int low,int high){
if (key < array[low] || key > array[high] || low > high) {
return -1;
}
int middle = (low+high)/2;
if(array[middle]>key){
return binSearch_2(key,array,low,middle-1);
}else if(array[middle]<key){
return binSearch_2(key,array,middle+1,high);
}else{
return array[middle];
}
}
//二分法(递归二}
public static void main(String[] args) {
int[] array ={1,2,3,4,6,7,8,9,10};
System.out.println( binSearch(2,array,0,8));
}
//递归方法
public static int binSearch_3(int key,int[] arr,int low, int high){
int mid = (high+low)/2;
if(low>high||arr[low]>key||arr[high]<key){
return -1;}
int rs = binSearch(key,arr,low,mid-1);
if(rs!=-1){
return rs;
}else if(arr[mid]==key){
return mid;
}else {
return binSearch(key, arr, mid+1, high);
}
}
}