package com.test;
public class BinarySearch {
private BinarySearch() {}
//test
public static void main(String[] args) {
Integer[] x = new Integer[]{-1, 0, 3, 5, 6, 9, 10, 23, 45, 67};
System.out.println(search(x, 9));
System.out.println(search(x, 67));
}
public static <T extends Comparable<T>> int search(T[] x, T key) {
return search(x, 0, x.length - 1, key);
}
// search recursively
private static <T extends Comparable<T>> int search(T[] x, int low, int high, T key) {
if (low <= high) {
int mid = low + ((high - low) >> 1);
if (key.compareTo(x[mid]) == 0) {
return mid;
} else if (key.compareTo(x[mid]) < 0) {
return search (x, low, mid-1, key);
} else {
return search(x, mid+1, high, key);
}
}
return -1;
}
}
二分搜索
最新推荐文章于 2024-09-06 16:24:56 发布