import java.util.ArrayList;
import java.util.List;
/*
* 折半查找
*/
public class binarySearch {
public binarySearch() {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10000; i += 2) { // 往list加入逐渐增大1-10000的所有偶数,作为实验数组,很明显,他是有序的!
list.add(i); // 这里当然也可用数组\
System.out.println(i);
}
int low = 0;
int high = list.size();
int key = 3334;
while (low <= high) {
int mid = (low + high) / 2;
if (key == list.get(mid)) {
System.out.println("此数值在list中的位置为:" + mid);
break;
}
if (key > list.get(mid)) {
low = mid + 1; // 当小于时,是low指针向后移动,high指针不变
}
if (key < list.get(mid)) {
high = mid - 1; // 当大于时,是high指针向前移动,low指针不变
}
}
if (low > high) {
System.out.println("没有查到结果!");
}
}
}