二分查找算法有两种解决方式,递归和非递归,很简单,直接看代码
package com.monster.binarysearch;
/**
* @author Monster
* @version v1.0
* @time 05-07-2021 20:55:54
* @description:
*/
public class NoRecur {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 6, 7, 8, 11, 16};
int binarySearch = binarySearch(arr, 16);
System.out.println("binarySearch = " + binarySearch);
int binarySearch2 = binarySearch2(arr, 0, arr.length - 1, 167);
System.out.println("binarySearch2 = " + binarySearch2);
}
// 非递归
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if(arr[mid] > target) {
right = mid - 1;
}else if(arr[mid] < target) {
left = mid + 1;
}else {
return mid;
}
}
return -1;
}
// 递归
public static int binarySearch2(int[] arr, int left, int right, int target) {
int mid = (left + right) / 2;
if(left > right)
return -1;
if(arr[mid] > target) {
return binarySearch2(arr, left, mid - 1, target);
}else if(arr[mid] < target) {
return binarySearch2(arr, mid + 1, right, target);
}else {
return mid;
}
}
}