# 算法——查找之二分查找

``````public static int recurSearch(Comparable[] orderArray, int low, int high, Comparable target) {
if (low > high) return -1;
int mid = (low + high) / 2;
int compared = orderArray[mid].compareTo(target);
if (compared > 0) { // 中值比目标大
return recurSearch(orderArray, low, mid - 1, target);
} else if (compared < 0) { // 中值比目标小
return recurSearch(orderArray, mid + 1, high, target);
} else {
return mid;
}
}``````

``````public static int iteratorSearch(Comparable[] orderArray, int low, int high, Comparable target) {
while (low <= high) {
int mid = (low + high) / 2;
int compared = orderArray[mid].compareTo(target);
if (compared > 0) {
high = mid - 1;
} else if (compared < 0) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}``````

``````public static void main(String[] args) {
final int NUM = 100000;
Integer[] a1 = new Integer[NUM];
Integer[] a2 = new Integer[NUM];
Integer[] a3 = new Integer[NUM];
Integer[] a4 = new Integer[NUM];
a1[0] = a2[0] = a3[0] = a4[0] = -1;
for (int i = 1; i < NUM; i++) {
a1[i] = (int) (Math.random() * NUM);
a2[i] = a1[i];
a3[i] = a1[i];
a4[i] = a1[i];
}

long startTime;
long endTime;

startTime = System.currentTimeMillis(); // 获取开始时间
for (int i = 0; i < NUM; i++) {
int position = OrderSearch.search(a1, 0, a1.length - 1, a1[i]);
if (!a1[position].equals(a1[i])) {
System.exit(-1);
}
}
endTime = System.currentTimeMillis();
System.out.println("顺序查找cost: " + (endTime - startTime) + " ms");

startTime = System.currentTimeMillis(); // 获取开始时间
QuickSort.sort2(a1);
assert isSorted(a1);
for (int i = 0; i < NUM; i++) {
int position = BinarySearch.recurSearch(a1, 0, a1.length - 1, a1[i]);
if (!a1[position].equals(a1[i])) {
System.exit(-1);
}
}
endTime = System.currentTimeMillis();
System.out.println("二分递归查找cost: " + (endTime - startTime) + " ms");

startTime = System.currentTimeMillis(); // 获取开始时间
QuickSort.sort2(a2);
assert isSorted(a2);
for (int i = 0; i < NUM; i++) {
int position = BinarySearch.iteratorSearch(a2, 0, a2.length - 1, a2[i]);
if (!a2[position].equals(a2[i])) {
System.exit(-1);
}
}
endTime = System.currentTimeMillis();
System.out.println("二分迭代查找cost: " + (endTime - startTime) + " ms");
}``````

``````顺序查找cost: 3078 ms