# 递归 -- 二分查找程序

java数据结构和算法中文第二版

OrdArray.java

package com.ch6.binarySearch;

public class OrdArray {

private long[] arr ;
private int nElems ;

public OrdArray(int cnt){
arr = new long[cnt] ;
nElems = 0 ;
}

public int size() {
return nElems ;
}

public int find(long key){
return recFind(key, 0, nElems-1) ;
}

public int recFind(long key, int lowerBound, int upperBound){

int curIn ;
curIn = (lowerBound + upperBound ) /2 ;
if (arr[curIn] == key){  //当前范围的中间即是查询关键字
return curIn ;
}else if (lowerBound > upperBound){ //没有找到，即开始下标大于结束下标，返回数组大小
return nElems ;
}else{
if (arr[curIn] < key){ //如果当前范围的中间的值小于关键字 ，则应该在curIn +1 到 upperBound中查找
return recFind(key, curIn +1, upperBound) ;
}else{//如果当前范围的中间的值大于关键字 ，则应该在lowerBound 到 curIn -1 中查找
return recFind(key, lowerBound, curIn -1) ;
}
}
}

public void insert(long key){
int i ;
for(i = 0; i < nElems; i++){
if (arr[i] > key){
break ;
}
}
for (int j = nElems; j > i; j--){
arr[j] = arr[j -1] ;
}
arr[i] = key ;
nElems++ ;

}

public void display(){
for (int i = 0; i < nElems; i++){
System.out.print( arr[i] + " ") ;
}
System.out.println(" ");
}
}

BinarySearchApp.java

package com.ch6.binarySearch;

import java.io.IOException;

public class BinarySearchApp {

/**
* @param args
*/
public static void main(String[] args) throws IOException{

int maxSize = 100;
OrdArray ordArr = new OrdArray(maxSize);
ordArr.insert(19);
ordArr.insert(72);
ordArr.insert(33);
ordArr.insert(45);
ordArr.insert(68);
ordArr.insert(53);
ordArr.insert(100);
ordArr.insert(30);

ordArr.display();
while (true) {
System.out.print("Enter a number: ") ;
int key = getInt() ;
int index = ordArr.find(key);
if (index != ordArr.size()) {
System.out.println(key + " is Found , index : " + index);
} else {
}
}
}

public static int getInt() throws IOException{

return Integer.parseInt(s) ;
}

}



19 30 33 45 53 68 72 100
Enter a number: 19
19 is Found , index : 0
Enter a number: 53
53 is Found , index : 4
Enter a number: 100
100 is Found , index : 7
Enter a number: 2
Enter a number:

04-10 849

09-27 883

08-14 1610

12-04 749

09-30 2840

03-10 5618

09-20 3458

05-25 1912

07-18 1483

05-29 1456