java实现二叉查找

import java.util.Stack;

/**
 * 使用栈代替递归,用于放入栈的记录
 * @author Administrator
 *
 */
class Record
{
	private int first,last;
	public  Record(int first,int last)
	{
		this.first=first;
		this.last=last;
	}
	public int getFirst() {
		return first;
	}
	public void setFirst(int first) {
		this.first = first;
	}
	public int getLast() {
		return last;
	}
	public void setLast(int last) {
		this.last = last;
	}
	
}

public class BinarySearch {
	/**
	 * 递归二叉查找
	 * @param first 查找起始下标
	 * @param last   查找结束下标
	 * @param item   待查找元素
	 * @param a      待查找的有序数组
	 * @return  返回查找元素在数组中的小标,如果找不到则返回-1;
	 */
	public static int binarySearch(int first, int last, int item,int[] a) {
		int mid = (first + last) / 2;
		if (first > last)
			return -1;
		else if (item==a[mid])
			return mid;
		else if (item<a[mid])
			return binarySearch(first, mid - 1, item,a);
		else
			return binarySearch(mid + 1, last, item,a);
	}
	
	/**
	 * 迭代二叉查找
	 * @param first 查找起始下标
	 * @param last   查找结束下标
	 * @param item   待查找元素
	 * @param a      待查找的有序数组
	 * @return  返回查找元素在数组中的小标,如果找不到则返回-1;
	 */
	public static int binarySearchNoRecursion(int first, int last, int  item,int[] a) {
		int mid;
		while (first <= last) {
			mid = (first + last) / 2;
			if (item<a[mid])
				last = mid - 1;
			else if (item>a[mid])
				first = mid + 1;
			else
				return mid;
		}
		return -1;

	}

	/**
	 * 使用栈代替递归
	 * @param first
	 * @param last
	 * @param item
	 * @return
	 */
	public static int binarySearchStack(int first,int last,int item,int[] a)
	{
		Stack<Record> stack=new Stack<Record>();
		int index = -1;
		boolean done=false;
		stack.push(new Record(first, last));
		while(!done&&!stack.isEmpty())
		{
			Record topRecord=stack.pop();
			first=topRecord.getFirst();
			last=topRecord.getLast();
			int mid=(first+last)/2;
			if(first>last)
			{
				index=-1;
				done=true;
				
			}
			else if(item==a[mid])
			{
				index=mid;
				done=true;
			}
			else {
				if(item<a[mid])
					stack.push(new Record(first, mid-1));
				else 
					stack.push(new Record(mid+1, last));
			}
		}
		return index;
	}
	public static void main(String[] argv)
	{
		int[] a=new int[]{1,3,5,7,9};
		System.out.println(binarySearch(0, a.length-1, 5, a));
		System.out.println(binarySearchNoRecursion(0, a.length-1, 2, a));
		System.out.println(binarySearchStack(0, a.length-1, 3, a));
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值