public class BinarySearch {
//非递归
public static int binSearch1(int[] arr, int target) {
if(arr == null || arr.length == 0)
return -1;
int left = 0, right = arr.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(arr[mid] == target) {
return mid;
}
if(arr[mid] < target) {
left = mid + 1;
}
if(arr[mid] > target) {
right = mid - 1;
}
}
return -1;
}
//递归
public static int binSearch2(int[] arr, int target, int left, int right) {
if(arr == null || arr.length == 0)
return -1;
if(left > right) {
return -1;
}
int mid = (left + right) / 2;
if(arr[mid] == target) {
return mid;
}
if(arr[mid] > target) {
return binSearch2(arr, target, left, mid-1);
}
if(arr[mid] < target) {
return binSearch2(arr, target, mid+1, right);
}
return -1;
}
public static void main(String[] args) {
int[] testArr = new int[]{1,2,3,5,8,9,12,13,15,20};
System.out.println(binSearch1(testArr, 3));
System.out.println(binSearch2(testArr, 3, 0, 10));
}
}
二分查找的递归和非递归实现
最新推荐文章于 2024-04-10 22:53:30 发布