<span style="font-size:18px;">package com.hechao;
import java.util.Comparator;
/**
* 我的工具类
* @author hechao
*
*/
public class MyUtil {
/**
* 私有构造器,不能创建对象,静态方法用类名.方法名调用
*/
private MyUtil(){
throw new AssertionError();
}
/**
* 二分查找
* <T extends Comparable<T>> 泛型参数(限定T必须是Comparable类型)
* @param array 元素升序排列的数组
* @param key 要查找的元素
* @return 如果找到了返回元素的位置, 没找到返回-1
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key){
int low = 0, high = array.length - 1;
int mid;
while(low <= high){
mid = (high - low) / 2 + low;
//mid = (high + low) >>> 1;
if(key.compareTo(array[mid]) == 0){
return mid;
}
if(key.compareTo(array[mid]) > 0){
low = mid + 1;
}
if(key.compareTo(array[mid]) < 0){
high = mid - 1;
}
}
return -1;
}
/**
* 二分查找
* <T> 泛型参数
* @param array 元素升序排列的数组
* @param key 要查找的元素
* @param comp 比较器对象
* @return 如果找到了返回元素的位置, 没有找到返回-1
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key, Comparator<T> comp){
return binarySearch(array, key, new Comparator<T>(){
@Override
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
});
}
}
</span>