堆的简单实现

来源:互联网 发布:怎么样修改淘宝会员名 编辑:程序博客网 时间:2024/05/22 14:39
 
package heap;/**堆是有如下特点的二叉树: * 1.它是完全二叉树, * 2.它常用一个数组实现,也可以用链表实现 * 3.每一个节点的关键字都大于它的子节点*/public class Heap {private Node [] heapArray; //采用数组private int maxSize;//最大的容量private int currentSize;//当前的容量/** * @param maxSize 当前堆的最大的容量 * */public Heap(int maxSize){this.maxSize=maxSize;heapArray=new Node[maxSize];currentSize=0;}/**获取当前的容量 */public int size(){return currentSize;}/** * 判断当前堆是否为空 * */public boolean isEmpty(){if(currentSize==0){return true;}else{return false;}}/** * 判断当前堆是 已满 * */public boolean isFull(){if(currentSize==maxSize){return true;}else{return false;}}/**插入元素 * @param node 要插入的节点 */public boolean insert(Node node){if(isFull()){System.out.println("堆已满!");return false;}//把该节点放在堆的最后一个位置heapArray[currentSize]=node;moveUp(currentSize);//把该节点往上移currentSize++;return true;}/** * 把一个节点往上移动 * @param index  要上移节点的下标 * */public void moveUp(int index) { if(index==0){ return; } int parent=(index-1)/2;//获取要移动的节点的父节点 Node node=heapArray[index];//获取要移动的节点 while(index>0&&node.getKey()>heapArray[parent].getKey()){ heapArray[index]=heapArray[parent]; index=parent; parent=(parent-1)/2; }heapArray[index]=node;}/**移除节点 */public Node remove(){if(isEmpty()){System.out.println("堆为空,移除失败");return null;}Node node=heapArray[0];heapArray[0]=heapArray[--currentSize];moveDown(0);return node;}/**元素向下移 * @param index 要往上移的节点的下标*/public void moveDown(int index){int large;Node node=heapArray[index];//临时保存要下一的节点while(index<=(currentSize-1)/2){//要保证下移的节点至少有一个子节点int left=index*2+1;int right=left+1;if(right<currentSize&&heapArray[left].getKey()<heapArray[right].getKey()){large=right;}else{large=left;}if(node.getKey()>heapArray[large].getKey()){break;}heapArray[index]=heapArray[large];index=large;}heapArray[index]=node;}public static void main(String[] args) {Heap heap=new Heap(10);heap.insert(new Node(8));heap.insert(new Node(45));heap.insert(new Node(2));heap.insert(new Node(7));heap.insert(new Node(96));heap.insert(new Node(74));heap.insert(new Node(63));heap.insert(new Node(34));heap.insert(new Node(85));while(!heap.isEmpty()){Node node=heap.remove();int key=node.getKey();System.out.print(key+" ");}}}


package heap;public class Node {private int key;public Node(int key){this.key=key;}public void setKet(int key){this.key=key;}public int getKey(){return key;}}


0 0
原创粉丝点击