一、Java实现二分查找【递归】
public static int binarySearchRecursion(int[] arr, int target, int left, int right) {
if(left > right)
return -1;
int mid = (left + right) / 2;
int midVal = arr[mid];
if(target > midVal)
return binarySearchRecursion(arr, target, mid + 1, right);
else if(target < midVal)
return binarySearchRecursion(arr, target, left, mid - 1);
else
return mid;
}
二、Java实现二分查找【非递归】
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = (left + right) / 2;
int midVal = arr[mid];
if(target < midVal)
right = mid - 1;
else if(target > midVal)
left = mid + 1;
else {
return mid;
}
}
return -1;
}
三、测试
public static void main(String[] args) {
int arr[]= { 1, 8, 10, 89, 1000,1000, 1234 };
System.out.println(binarySearch(arr, 89));
}