问题:给定一个整数X和整数序列A0,A1,...,An,整数序列已经预先排序好了,求下标i使得Ai=X,如果X不在序列中则返还i=-1
分析:由于序列已经是排序好的了,所以优先验证X是否是居中的元素。如果是,则答案找到了。如果X小于居中元素,那么可以应用同样的策略继续折半查找居中元素左边的子序列;同理,如果X大于居中的元素,那么就查找居中元素右边的子序列。
全部代码:
public class BinarySearch {
private static final Integer[] ARRAY_SEARCH = new Integer[]{1, 14, 25, 37, 56, 69, 72, 88, 93};
private static final Integer TARGET_50 = 50;
private static final Integer TARGET_88 = 88;
public static void main(String[] args) {
// TODO Auto-generated method stub
int findIndex = -100;
findIndex = binarySearch(ARRAY_SEARCH, TARGET_50);
System.out.println("Search TARGET_50 result: " + findIndex);
findIndex = binarySearch(ARRAY_SEARCH, TARGET_88);
System.out.println("Search TARGET_88 result: " + findIndex);
}
public static <AnyType extends Comparable<? super AnyType>> int binarySearch(AnyType[] array, AnyType target) {
final int NOT_FOUND = -1;
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid].compareTo(target) < 0) {
low = mid +1;
} else if (array[mid].compareTo(target) > 0) {
high = mid - 1;
} else {
return mid;
}
}
return NOT_FOUND;
}
}
输出结果:
Search TARGET_50 result: -1
Search TARGET_88 result: 7