递归 -- 二分查找程序

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:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值