優先順序隊列,數值越小,優先順序越高。優先順序越高的最新被刪除,區別於普通的隊列先進先出。
演算法如下:
定義結點:
class Node {private int iData;public Node(int iData) {this.iData = iData;}public int getIData() {return iData;}public void setIData(int data) {iData = data;}}
public class PriorityQueue_Heap {private Node[] heapNode;private static final int max_size = 50;// 最大結點數private int current_index = 0;private static final int max_Value = 50;//結點最大值public PriorityQueue_Heap(int size) throws InterruptedException {current_index = 0;heapNode = new Node[max_size];Random random = new Random();for (int i = 0; i < size; i++) {int value = random.nextInt(max_Value);buildMinHeap(value);}}/** * 構造最小堆 * * @param value * @return */public boolean buildMinHeap(int value) {Node node = new Node(value);if (current_index == max_size) {return false;} else {heapNode[current_index] = node;tickleUp(current_index);current_index++;return true;}}/** * 向上調整 * * @param current_index */public void tickleUp(int current_index) {int parent = (current_index - 1) / 2;// 找到當前節點的父節點// 暫存當前節點值Node bottom = new Node(heapNode[current_index].getIData());while (current_index > 0&& heapNode[parent].getIData() > bottom.getIData()) {// 父節點下移heapNode[current_index].setIData(heapNode[parent].getIData());current_index = parent;parent = (current_index - 1) / 2;}heapNode[current_index] = bottom;}/** * 向下調整 * * @param index */public void tickleDown(int index) {int minChild;//當前結點兩個孩子結點中大的那個下標Node top = heapNode[index];while (index < current_index / 2) {int leftChild = 2 * index + 1;int rightChild = leftChild + 1;// 如果右節點存在,並且由節點大於左節點。則右節點就是最大的節點if (rightChild < current_index&& heapNode[rightChild].getIData() < heapNode[leftChild].getIData()) {minChild = rightChild;} else {minChild = leftChild;}// 找到了這樣的節點比位元組的還小if (top.getIData() < heapNode[minChild].getIData()) {break;} else {heapNode[index] = heapNode[minChild];index = minChild;}}// end whileheapNode[index] = top;}/** * 取優先順序最高的節點 * * @return */public int min() {return heapNode[0].getIData();}/** * 往大堆中插入一個新節點 * * @param key */public void insert(int key) {buildMinHeap(key);}/** * 從大堆中刪除優先順序最高的節點,同時把最後一個節點放入到根節點,然後調整 * * @param key */public Node delMin() {Node root = heapNode[0];if (current_index == 0) {return null;}heapNode[0] = heapNode[--current_index];// 向下重新整理tickleDown(0);return root;}/** * 顯示大堆 */public void disHeap() {System.out.print("heapArray:");for (int i = 0; i < heapNode.length; i++) {if (heapNode[i] != null) {System.out.print(heapNode[i].getIData() + ",");} elsebreak;}System.out.println(" ");}public static void main(String[] args) throws InterruptedException {PriorityQueue_Heap ph = new PriorityQueue_Heap(10);ph.disHeap();System.out.println("min:" + ph.min());int inValue = 20;System.out.println("insert value:"+inValue);ph.insert(inValue);ph.disHeap();System.out.println("del value:"+inValue);System.out.println("the min="+ph.delMin().getIData());ph.disHeap();}