二分查找

二分查找:实现中采用左闭右闭区间。在findPos中,如果要查找的数在数组中有重复值,则返回的是最靠近数组中间位置的值。在findPosFirst中,如果有重复值返回位置最前的值。在findPosLast中,如果有重复值返回位置最后的值。


public class Bsearch 
{
	public Bsearch(){}
	
	public static int[] array = new int[]{};
	
	
	public static void search(int t)
	{
		int res = findPos(t,0,array.length-1);
		if(res==-1)
			System.out.println("Find the right value:"+"\t"+"Can not find "+t+" in the array!");
		else
			System.out.println("Find the right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
		
		res = findPosFirst(t,0,array.length-1);
		if(res==-1)
			System.out.println("Find the first right value:"+"\t"+"Can not find "+t+" in the array!");
		else
			System.out.println("Find the first right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
		
		res = findPosLast(t,0,array.length-1);
		if(res==-1)
			System.out.println("Find the last right value:"+"\t"+"Can not find "+t+" in the array!");
		else
			System.out.println("Find the last right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
	}
	
	public static int findPos(int t, int start, int end)
	{
		if(start>end) return -1;
		int l = start;
		int h = end;
		int mid = (l+h)/2;
		if(array[mid]<t)
		{
			l = mid+1;
			return findPos(t,l,h);
		}
		else if(array[mid]==t)
		{
			return mid;
		}
		else
		{
			h = mid-1;
			return findPos(t,l,h);
		}
	}
	
	
	public static int findPosFirst(int t, int start, int end)
	{
		int pos = -1;
		int mid;
		while(start<=end)
		{
			mid = (start+end)/2;
			if(array[mid]>t) end = mid-1;
			else if(array[mid]<t) start = mid+1;
			else
			{
				pos = mid;
				end = mid-1;
			}
		}
		return pos;
	}
	
	public static int findPosLast(int t, int start, int end)
	{
		int pos=-1;
		int mid;
		while(start<=end)
		{
			mid = (start+end)/2;
			if(array[mid]>t) end = mid-1;
			else if(array[mid]<t) start = mid+1;
			else 
			{
				pos = mid;
				start = mid+1;
			}
		}
		return pos;
	}
	
	public static void main(String[] args)
	{
		array = new int[]{1,2,2,2,2};
//		array = new int[]{1,2,3,4,5};
		int t = 2;
		search(t);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值