折半查询

本文深入探讨了折半查询算法的实现原理,强调了数组必须有序的前提条件,并通过具体代码示例展示了如何在Java中实现折半查询。文章还提供了一个测试类,用于验证折半查询算法的正确性。

折半查询,(数组必须是有序的)

public class Utils {

	private static int binaryQueryCompote(int[] buf, int n, int sta, int end) {
		if(sta > end) {
			return -1;
	}
		if(sta == end) {
			if(buf[sta] == n) {
				return sta;
			}else {
				return -1;
			}
		}

		int i = (end + sta) / 2;
		
		if(buf[i] == n) {
			return i;
		}else if(buf[i] < n){
			return binaryQueryCompote(buf, n, i + 1, end);
		}else {
			return binaryQueryCompote(buf, n, sta, i - 1);
		}
	}
	
	public static int binaryQuery(int[] buf, int n) {
		return binaryQueryCompote(buf, n, 0, buf.length -1);
	}
}

测试类

public class Test {

	public static void main(String[] args) {
		/*
		 * 	1. 找出数组中的元素
		 * 	2. 如果要使用折半查询,则数组元素必须有序
		 * */ 
		Scanner scanner = new Scanner(System.in);
		
		int[] buf = {18, 27, 33, 48, 57, 57, 66, 68, 70, 76, 86, 94, 95, 96, 108, 116, 129, 154, 158, 166, 181, 185, 185, 200, 200, 208, 220, 233, 239, 296, 300, 306, 312, 315, 316, 321, 329, 350, 351, 354, 362, 378, 379, 379, 381, 388, 411, 415, 423, 429, 471, 481, 483, 483, 483, 499, 499, 513, 515, 526, 529, 533, 540, 546, 566, 567, 578, 589, 589, 610, 615, 641, 656, 666, 693, 702, 703, 730, 742, 758, 761, 778, 801, 803, 814, 828, 835, 837, 839, 840, 845, 876, 899, 906, 919, 921, 930, 933, 949, 970};
		
		System.out.print("请输入您要查询的数:");
		int n = scanner.nextInt();
		
		System.out.println(Utils.binaryQuery(buf, n));
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值