以下代码是参考网上的,然后自己改了一点
package sorter;import java.util.Comparator;
/**
* 上面的代码中给出了折半查找的两个版本, 一个用递归实现,一个用循环实现。
*
* @className: Sorter2
* @description:
* @author: singleton-zw
* @createDate: 2016年3月4日-下午5:36:08
* @version: v1.0
* @Copyright (c)-2016
*/
public class Sorter2 {
/**
* 折半查找 需要注意的是 源数据必须的有序的 这里使用了 Comparator 来排序
*
* @methodsDescription:
* @methodName: main
* @param args
* @author: singleton-zw
* @return: void
*/
public static void main(String[] args) {
Integer score[] = { 67, 69, 11, 98, 75, 87, 89, 10, 99, 100 };
int score1[] = { 67, 69, 75, 87, 89, 99, 100 };
Comparator<Integer> comp = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// 使用默认的排序方法
return 0;
}
};
int binarySearch = binarySearch(score, 10, comp);
System.out.println("该数据位于:" + (binarySearch + 1));
System.out.println(BiSearch(score1, score1.length, 87));
}
public static <T extends Comparable<T>> int binarySearch(T[] x, T key) {
return binarySearch(x, 0, x.length - 1, key);
}
// 使用循环实现的二分查找
public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {
int low = 0;
int high = x.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int cmp = comp.compare(x[mid], key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
// 使用递归实现的二分查找
private static <T extends Comparable<T>> int binarySearch(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 binarySearch(x, low, mid - 1, key);
} else {
return binarySearch(x, mid + 1, high, key);
}
}
return -1;
}
/**
*
* @methodsDescription:
* @methodName: BiSearch
* @param r
* 数据源 必须是有序的
* @param n
* 数据个数
* @param k
* 查询的关键字
* @return
* @author: singleton-zw
* @return: int 位于第几个
*/
static int BiSearch(int r[], int n, int k) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (r[mid] == k)
return mid;
else if (r[mid] < k)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}