递归 -- 二分查找程序

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

 

递归的二分查找和非递归的二分查找有相同的大O效率:O(logN) ,但是代码简洁,速度可能慢点 。

 

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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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 {
				System.out.println(key + " is not Found.");
			}
		}
	}
	
	public static int getInt() throws IOException{
		
		InputStreamReader isr = new InputStreamReader(System.in) ;
		BufferedReader br = new BufferedReader(isr) ;
		String s = br.readLine() ;
		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
2 is not Found.
Enter a number:

阅读更多
个人分类: java 数据结构
上一篇递归 --变位数 --字符串相关
下一篇递归 -- 汉诺塔
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭