二分查找

来源:互联网 发布:淘宝代销手动分账 编辑:程序博客网 时间:2024/06/12 01:22
/** * 二分查找 * <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>() {@Overridepublic 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;}

0 0
原创粉丝点击