今天上午闲来无事,重温了一遍数组,接触到一种从来没有用过的查询方式:二分查找,也称折半查找。

初次看到这个二分查找,不明其意,主要是我笨。于是为了弄懂它,我去搜索了。

不得不说。搜索还是有用的,也让我知道二分查找的优点,查找速度会比遍历更快!但是它也有着致命的缺点。
要求顺序存储结构且必须按照关键字大小有序排列。
好了,虽然它有缺点,但是对于符合条件的数组或者集合来说还是很有用的。
下面我决定做一个测试,来验证它是否比普通遍历更快!
//这是普通的遍历方法
public int find(int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
// 二分查找方法
public int findByHalf(int value) {
int start = 0;
int end = array.length;
while (end >= start) {
int index = (start + end) / 2;
if (array[index] == value) {
return index;
} else if (array[index] > value) {
end = index - 1;
} else if (array[index] < value) {
start = index + 1;
}
}
return -1;
}
public static void main(String[] args) {
//new对象并给数组插入数据
UseArray ua = new UseArray();
for (int i = 1; i <= ua.max; i++) {
ua.insert(i);
}
long beginTime1 = System.currentTimeMillis();
ua.find(5);//普通查找
long endTime1 = System.currentTimeMillis();
long beginTime2 = System.currentTimeMillis();
ua.findByHalf(5);//二分查找
long endTime2 = System.currentTimeMillis();
System.out.println("遍历查找所用时间: " + (endTime1 - beginTime1)
+ " 二分查找所用时间: " + (endTime2 - beginTime2));
}
结果是:
Paste_Image.png
网友评论