//把迭代用在有序数组二分法查找中,递归的二分法查找更简洁,但速度可能会慢一点
//分治算法方法中包含两个对自身的递归调用,分别对应于问题的两个部分,在二分法查找中就有两个
//这样的调用,但是只有一个真的执行。调用哪个取决于关键字的值
//后面将会遇到归并排序,她是真正执行了两个递归调用(分成两半的数组分别进行排序)
public class BinarySearchApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OrdArray oa=new OrdArray(20);
oa.insert(72);
oa.insert(90);
oa.insert(45);
oa.insert(126);
oa.insert(54);
oa.insert(99);
oa.insert(144);
oa.insert(27);
oa.insert(135);
oa.insert(81);
oa.insert(18);
oa.insert(108);
oa.insert(9);
oa.insert(117);
oa.insert(63);
oa.insert(36);
oa.display();
int searchKey=27;
if(oa.find(searchKey)!=oa.size())
System.out.println("Found"+searchKey+": "+oa.find(searchKey));
else System.out.println("can not find it "+searchKey);
}
}
class OrdArray{
private int items;
private long[] array;
private int s;
OrdArray(int max){
s=max;
array=new long[s];
}
public boolean isFull(){
return items==s;
}
public int size(){
return items;
}
public void insert(long value){
int i,j;
for(i=0;i<items;i++){
if(value<array[i])
break;
}
for(j=items;j>i;j--){
array[j]=array[j-1];
}
array[i]=value;
items++;
}
public void display(){
for(int i=0;i<items;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
public int find(long searchKey){
return recFind(searchKey,0,items-1);
}
public int recFind(long searchKey,int lowBound,int highBound){
int k=(lowBound+highBound)/2;
if(array[k]==searchKey)
return k;
else if(lowBound>highBound)
return items;
else{
if(searchKey>array[k])
return recFind(searchKey,k+1,highBound);
else
return recFind(searchKey,lowBound,k-1);
}
}
}