package test;
/**
* 二分查找的两种写法(递归和非递归)
*/
public class BinarySearchTest {
public static boolean isSorted(Comparable[] arr) {
int N = arr.length;
for (int i = 0; i < N-1; i++) {
if (arr[i].compareTo(arr[i+1]) > 0)
return false;
}
return true;
}
/**
* 递归写法
* @param arr 数组需要有序
* @param target 目标元素
* @return if return -1, target not in arr, else return the index of the target
*/
public static int search(Comparable[] arr, Comparable target) {
return search(arr, target, 0, arr.length-1);
}
/**
* 非递归写法
* @param arr
* @param target
* @return
*/
public static int search2(Comparable[] arr, Comparable target) {
assert isSorted(arr);
int lo = 0, hi = arr.length-1;
while (lo <= hi) {
int mid = lo + (hi - lo);
int cmp = target.compareTo(arr[mid]);
if (cmp > 0) lo = mid + 1;
else if (cmp < 0) hi = mid - 1;
else return mid;
}
return -1;
}
private static int search(Comparable[] arr, Comparable target, int lo, int hi) {
assert isSorted(arr); // 需要在VM options中添加 -ea 或者 -enableassertions 开启断言
if (lo > hi) return -1;
int mid = lo + (hi - lo);
int cmp = target.compareTo(arr[mid]);
if (cmp > 0) lo = mid + 1;
else if (cmp < 0) hi = mid - 1;
else return mid;
return search(arr, target, lo, hi);
}
public static void main(String[] args) {
Comparable[] arr = new Integer[] {2, 3, 5, 23, 34, 56, 77};
System.out.println(search(arr, 77));
System.out.println(search2(arr, 77));
}
}
二分查找法的两种实现(递归和非递归)
最新推荐文章于 2022-03-23 20:34:30 发布