package cnic.cn.impl;
public class ArrayTest {
public static void main(String[] args) {
int key=11;
int time=0;
int[] array = new int[10];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 3;
array[4] = 4;
array[5] = 5;
array[6] = 6;
array[7] = 7;
array[8] = 8;
array[9] = 9;
int lower = 0;
int upper = 9;
int curIn;
//二分法查找
while(true){
curIn = (lower+upper)/2;
if(array[curIn]==key){
time++;
System.out.println("the index is "+curIn+"compare time is"+time);
return;
}else if(lower>upper){
time++;
System.out.println("there is no match,the comparable time is"+time);
return;
}else if(array[curIn]>key){
time++;
upper = curIn-1;
}else if(array[curIn]<key){
time++;
lower = curIn+1;
}
}
}
}
对于有序数组,二分法可以明显的加快查找效率。
二分法查找有序数组
最新推荐文章于 2024-02-01 23:42:26 发布