二分查找折半查找排序

在一个有序的数组中,折半查找一个元素key,如果能找到返回数组的下表,如果找不到,返回-1。

实现如下所示:

/**
 * 二分查找法
 * @author jcm
 *	2016年8月6日
 */
public class BinarySerach {

	public static void main(String[] args) {
		int a[] = {13,19,32,35,56,75,97,98,112,332,789};
		int flag = binarySearch(a,19);
		if (flag == -1)
			System.out.println("没有找到元素值");
		else
			System.out.println("在数组的第"+flag+"处找到元素,值是"+a[flag]);
	}
	private static int binarySearch(int a[],int key){
		int low=0;
		int high = a.length-1;
		int mid;
		while(low<=high){
			mid = (low+high)/2;
			System.out.print("最低位是"+low+" 最高位是"+high+" 中间位置是"+mid);
			System.out.println();
			if (key == a[mid])
				return mid;
			else if (key>a[mid])
				low = mid +1;
			else
				high = mid-1;
		}
		return -1;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值