【代码积累-2】binary search

import java.util.Arrays;


public class Test {
	int test[] = {49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51,111,222,333,444,546,768};
	
	public void test() {	
		//排序
		Arrays.sort(test);
		
		//二分查找
		int result = binarySearch1(test,12);
		
		System.out.println("index = "+result);
	}
	
	public int binarySearch0(int[] a,int key) {
		return binarySearchImpl0(a,key,0,a.length-1);
	}
	
	public int binarySearch1(int[] a,int key) {
		return binarySearchImpl1(a,key,0,a.length-1);
	}
	
	/*先用递归实现*/
	private int binarySearchImpl0(int[] a,int key,int lowindex,int highindex) {
		/*int[] a是经过排序的数组,通常是升序排列,如果key超出范围,直接返回,函数只处理在范围内的查找不到的异常*/
		if( key > a[highindex] || key < a[lowindex] ) {
			return -1;
		}
		
		if( lowindex > highindex ) {
			return -1;
		}
		
		int midindex = (lowindex+highindex)>>>1;

		if( key < a[midindex] ) {
			return binarySearchImpl0(a,key,lowindex,midindex-1);
		} else if( key > a[midindex] ) {
			return binarySearchImpl0(a, key, midindex+1, highindex);
		} else {
			return midindex;
		}
		
		/*小结:
		 * 1、递归法的好处是函数逻辑结构简单
		 * 2、缺点是如果数组体量很大,可能会造成函数栈溢出
		 *    制造栈溢出的方法:1、申请一个大的local变量  2、深度递归*/
	}
	
	/*使用循环实现*/
	private int binarySearchImpl1(int[] a,int key,int lowindex,int highindex) {
		int midindex = 0;
		int low = lowindex;
		int high = highindex;
		
		/*循环截止条件:lowindex > highindex*/
		while( low <= high ) {
			midindex = (low+high) >>>1;
			
			if( key < a[midindex] ) {
				high = --midindex;
			} else if( key > a[midindex] ) {
				low = ++midindex;
			} else {
				return midindex;
			}
		}
		
		return -1;
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值