您的位置:首页 > 编程语言 > Java开发

java实现二叉查找

2013-05-09 20:01 211 查看
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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: