二分法查找(折半查找)

概念

有序数组中,查找目标值的位置

效果图

在这里插入图片描述

代码

public class BinarySearch {
	public static void main(String[] args) {
		//从方法,获取一个乱序数组
		int[] a = suiJi();
		//对a数组排序
		Arrays.sort(a);//优化的快速排序
		System.out.println(Arrays.toString(a));
		while(true) {
			System.out.print("查找的目标值:");
			int t = new Scanner(System.in).nextInt();
			//从a数组中,查找t的位置(二分法查找)
			int index = binarySearch(a, t);
			System.out.println(index);
		}
	}

	private static int[] suiJi() {
		//随机产生5+ [0,6)范围整数n
		int n = 5+ new Random().nextInt(6);
		//新建int[]数组,长度n
		int[] a = new int[n];
		//遍历数组,填入100内随机整数
		for (int i = 0; i < a.length; i++) {
			a[i] = new Random().nextInt(100);
		}
		return a;
	}

	private static int binarySearch(int[] a, int t) {
		/*
		 *  0           mid             7
		 * [16, 21, 30, 36, 39, 70, 70, 92]
		 *  lo                          hi
		 *                    
		 */
		int lo = 0;
		int hi = a.length-1;
		int mid;
		while(lo <= hi) {
			mid = (lo+hi) / 2;
			if(a[mid] < t) {
				lo = mid+1;
			} else if(a[mid] > t) {
				hi = mid-1;
			} else {
				return mid;
			}
		}
		//避免lo是0,加1后,再加负号
		return -(lo+1); // -(插入点+1)
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值