/**
* 二分查找
* <T extends Comparable<T>> 泛型参数(限定T必须是Comparable类型)
* @param array 元素升序排列的数组
* @param key 要查找的元素
* @return 如果找到了返回元素的位置, 没找到返回-1
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key) {
return binarySearch(array, key, new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
});
}
/**
* 二分查找
* <T> 泛型参数
* @param array 元素升序排列的数组
* @param key 要查找的元素
* @param comp 比较器对象
* @return 如果找到了返回元素的位置, 没有找到返回-1
*/
public static <T> int binarySearch(T[] array, T key, Comparator<T> comp) {
int low = 0, high = array.length - 1;
while(low <= high) {
int mid = (low + high) >>> 1; // int mid = (high - low) / 2 + low;
if(comp.compare(array[mid], key) == 0) return mid;
else if(comp.compare(key, array[mid]) < 0) high = mid - 1;
else low = mid + 1;
}
return -1;
}
/**
* 二分查找(递归版)
*/
public static <T> int binarySearch2(T[] array, T key, Comparator<T> comp) {
return binarySearch2(array, key, 0, array.length - 1, comp);
}
private static <T> int binarySearch2(T[] array, T key, int low, int high, Comparator<T> comp) {
if(low <= high) {
int mid = (low + high) >>> 1; // int mid = (high - low) / 2 + low;
if(comp.compare(array[mid], key) == 0) return mid;
else if(comp.compare(key, array[mid]) < 0)
return binarySearch2(array, key, low, mid - 1, comp);
else
return binarySearch2(array, key, mid + 1, high, comp);
}
return -1;
}
二分查找
最新推荐文章于 2022-03-22 18:31:50 发布