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)); } }
相关文章推荐
- java实现二叉查找
- Java 二叉查找(排序)树 创建 以及中序和层序遍历
- 二分查找的Java实现
- JAVA实现 查找有环链表起始位置
- 用java实现折半查找
- 【剑指offer——JAVA实现】二维数组中的查找
- 算法 -- Java实现二分(折半)查找(图解 + 代码实现)
- 二分法查找JAVA实现
- 二叉查找树--查找、删除、插入(Java实现)
- 8、二分查找 JAVA实现
- 二叉查找数的实现(算法导论)
- 剑指offer--面试题3:二维数组的查找--Java实现
- java实现创建链表以及插入节点,查找结点,删除节点等操作
- JAVA 二分法查找实现
- Trie树的建立—查找字典中以特定字符串开头的单词数量(java实现)
- Java实现查找输入整数二进制中1的个数
- 各种查找的实现Java
- 堆排序(JAVA)实现和杨氏矩阵查找
- 平衡二叉树平衡二叉树(AVL)--查找、删除、插入(Java实现)
- Atitit.upnp SSDP 查找nas的原理与实现java php c#.net c++