二分查找最大比较次数

      对有序数组进行查找,一般采用折半查找,也叫二分查找。它的最大比较次数,或者查找一个数组中不存在的数据的最大比较次数,如下:

 

public class BinarySearchNum 
{
	private static int Length = 9;
	
	public static void main(String[] args)
	{
		int size = 10;
		int low = 1;
		int high = 1;

		for(int i=0; i<Length; i++)
		{
			high = size;
			
			Compute(low, high);
			
			size = size * 10;
		}
	}
	
	public static void Compute(int low, int high)
	{
		int count = 0;
		int temp = high;
		
		while(low != high)
		{
			high = (low + high)/2;
			
			count++;
		}
		
		System.out.println(temp + "  " + count);
	}
}

 

 

输出结果为(前面数字为数组大小,后面数字为最大比较次数):

10  4
100  7
1000  10
10000  14
100000  17
1000000  20
10000000  24
100000000  27
1000000000  30

 

       后来想到一个问题,对有序数组的查找,是不是二分查找算法就是最快的呢?于是试了下“三分查找”,如下代码,结果比较次数比二分查找的次数多。如下代码:

 

public class TripleSearchNum 
{
	public static int Size = 1000;
	
	public static void main(String[] args)
	{
		int low = 1;
		int high = Size;
		int count = 0;
		
		while(low != high)
		{
			high = (low + high)/3;
			count = count + 2;
		}
		
		System.out.println(count);
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值