/**
* 递归实现二分查找
*时间复杂度O(logn)
*前提:数组有序
*如果找到target,返回相应的索引,未找到,返回-1
*
*/
public class BinarySearch {
public static int binarySearch(int[]arr,int l,int r,int target) {
//或者转换为long等类型即可
if(target==arr[mid])
return mid;
else if(target<arr[mid])
return binarySearch(arr,l, mid-1, target);
else
return binarySearch(arr, mid+1,r, target);
}
public static void main(String[] args) {
int [] arr= {1,3,4,5,6};
int result=binarySearch(arr, 0, arr.length-1, 3);
System.out.println(result);
}
* 递归实现二分查找
*时间复杂度O(logn)
*前提:数组有序
*如果找到target,返回相应的索引,未找到,返回-1
*
*/
public class BinarySearch {
public static int binarySearch(int[]arr,int l,int r,int target) {
if(l>r) return -1; //找不到返回-1
int mid=l+(r-l)/2;//最小值加上范围,用减法实现,这样不会产生整型溢出//或者转换为long等类型即可
if(target==arr[mid])
return mid;
else if(target<arr[mid])
return binarySearch(arr,l, mid-1, target);
else
return binarySearch(arr, mid+1,r, target);
}
public static void main(String[] args) {
int [] arr= {1,3,4,5,6};
int result=binarySearch(arr, 0, arr.length-1, 3);
System.out.println(result);
}
}
/**
*迭代实现二分查找
*O(logn),时间复杂度一样,但是性能略好
*前提:数组有序
*如果找到target,返回相应的索引,未找到,返回-1
*/
public class BinarySearch2 {
public int binartSearch2(int []arr,int n,int target) {
int l=0,r=n-1;
while(l<=r) {
int mid=l+(r-l)/2;
if(target==arr[mid])
return mid;
else if(target<arr[mid])
r=mid-1;
else {
l=mid+1;
}
}
return -1; //找不到返回-1
}
public static void main(String[] args) {
int [] arr= {1,3,4,5,6};
int n=arr.length;
BinarySearch2 search2=new BinarySearch2();
int result=search2.binartSearch2(arr, n, 3);
System.out.println(result);
}
}