1 Chapter 13 Priority Queues
2 Chap.13 Contents 13.1 Introduction 13.2 The PurePriorityQueue Interface 13.3 Implementations of the PurePriorityQueue Interface The Heap Implementation of the PurePriorityQueue Interface 13.4 Application: Huffman Codes
Introduction A priority queue (PQ) is an interface (property) in which access or deletion is of: the highest-priority element, according to some method of assigning priorities to elements.
4
5
6
The PurePriorityQueue Interface public interface PriorityQueue { /** * size 回傳 PurePriorityQueue 中元素的個數 */ int size ( )
8 /* isEmpty 看 PurePriorityQueue * 是否沒有元素. * * return true – if PurePriorityQueue * 沒有元素 ; * otherwise, return false ; */ boolean isEmpty ( )
9 /** * add 加元素到 PurePriorityQueue. * * The worstTime(n) is O(n). * element – 要插入 PurePriorityQueue 的元素 */ void add (E element)
10 /* getMin * 回傳 PurePriorityQueue 中的最高優先權元素 * * The worstTime(n) is O (1). * PurePriorityQueue 的最高優先權元素 * NoSuchElementException – * if PurePriorityQueue 是空的 */ E getMin ( )
11 /* removeMin * 從 PurePriorityQueue 移除具有最高優先權的元素 * * The worstTime(n) is O (log n). * 被移除的元素 * NoSuchElementException – * if PurePriorityQueue 是空的 */ E removeMin ( )
Implementations of The PurePriorityQueue Interface 有三種 data structures 可實 作之,分別是 : 1) linked list 2) tree set 3) heap
1. Use Linked List 13
14 public class LinkedPQ impelments PurePriorityQueue { LinkedList list ; Comparator comparator ;
15 public LinkedPQ() {list = new LinkedList ( ) ; comparator = null ; } public LinkedPQ (Comparator comp) {this() ; comparator = comp ;} public int size() { return list.size() ; } public E getMin() { return list.getFirst() ; } public E removeMin(){ return list.removeFirst() ;}
16
17 public void add (E element){ if /* 空或 element 優先權比最後的大 */ (list.isEmpty( ) || compare (element, list.get (list.size( ) – 1)) >= 0) /* 直接 add 此 element */ list.add (element) ; else {/* 找適當位置 add 使優先權由小到大 */ ListIterator itr = list.listIterator( ); while (itr.hasNext() && compare (element, itr.next( )) >= 0) ; /* 倒退一位, 再 add*/ itr.previous( ) ; itr.add (element) ; }} //end of add WorstTime (n) is linear in n.
18
19 2. Use Tree Set
20 public class TreeSetPQ implements PriorityQueue { TreeSet set; Comparator comparator; // the 2 constructors, size, isEmpty and compare // methods 與 LinkedPQ class 的類似 public TreeSetPQ (Comparator c) { comparator = c ; set = new TreeSet (c); } // one-parameter constructor
21 public void add (E element) {set.add (element);} public E getMin ( ) {return set.first( );} public E removeMin ( ) {E temp = set.first( ); set.remove (set.first( )); return temp;} } // end of class TreeSetPQ For these three methods, worst time (n) is logarithmic in n.
3. Use Heap 22
23
24 Heap [Collins English Dictionary] A collection of articles or mass of material gathered together in one place. 這定義用於 compiler, OS. Ex: Heap storage ( 堆 ) vs. stack storage ( 疊 ) in main memory.
25 但是, Data Structure 中的 Heap , 有不同的定義 : Heap 是一棵 tree , 且任何一個節點比 所有 descendants ( 後代 ) 都小
26
27
28
29 heap 不是 binary search tree! 因為對 root 而言 binary search tree 是 左小右大 heap 則是上 (root) 小 下 ( 左右 ) 大 這叫 min heap (minimal element at root) 另有 max heap (maximal element at root) 則是下 ( 左右 ) 小 上 (root) 大
30
31
32 下列的學生分數程式,創出 Heap 結構 , 並執行 Heap 動作 : add 和 removeMin 請輸入學生姓名及 GPA 或 ***( 結束 )”; Mary 4.0 (red indicates user input) John 3.5 *** 系統輸出如下 John 3.5 Mary 4.0
33 public static void main(String[] args){ final String PROMPT= “ 請輸入學生姓名及 GPA 或 ***( 結束 )”; final String RESULTS =“\n 學生姓名及 GPA 如下 ” ; String line ; Heap heap = new Heap ( ) ; BufferedReader keyboardReader = new BufferedReader (new InputStreamReader(System.in) ) ; try{ while(true) {System.out.print (PROMPT) ; line = keyboardReader.readLine() ; if (line.equals(“***”)) break ; heap.add (new Student(line) );} //while system.out.println (RESULTS); while(!heap.isEmpty()) System.out.println (heap.removeMin() ) ; }//try catch(Exception e){ System.out.println(e) ;} } // end of main
34 import java.util.* ; public class Student implements Comparable { protected String name ; protected double gpa ; /** Student 從特定的 String s 初始化 Student object. * s – String 初始化 Student object. NullPointerException, NoSuchElementException, * NumberFormatException */ public Student (String s){ StringTokenizer tokens = new StringTokenizer(s) ; name = tokens.nextToken() ; gpa = Double.parseDouble( tokens.nextToken() ) ; } // constructor public String toString() {return name+“ “+ gpa;} } // end of class Student
The Heap Implementation of the PurePriorityQueue Interface
36
37
38
39
40
41
42
43
44 Protected void percolateUp(){ // 設定 child 為 最後一個 node (size -1) int child = size -1; int parent; Object temp ; while(child > 0){ parent = (child-1)/2; // 如果 parent <= child 不用做了 if(compare(heap[parent],heap[child] <= 0) break; // 否則 swap parent 與 child temp=heap[parent];heap[parent]=heap[child];heap[child]=temp; /*child 向上走一步 */ child = parent; }//end while } //end of percolateUp
45
46
47
48
49
50 Protected void percolateDown(int start){ // parent 為 tree 的 root (index 0 ) // child 為 root 的左子樹 int parent = start, child = 2*parent + 1; Object temp ; while(child < size){ // 如 child 有右兄弟 且 右兄弟較小 則設定 child 為右兄弟 if(child < size – 1 && compare(heap[child],heap[child+1])> 0) child ++; // 如 parent <= child 不用再比了 if(compare(heap[parent],heap[child] <= 0) break; // 否則 swap parent 與 child temp = heap[child]; heap[child] = heap[parent];heap[parent] = temp; // child 向下走一步 parent = child; child = 2 * parent +1; }//while } // end of percolateDown
51
實際儲存於 array: index: 0 1 2
Application: Huffman Codes
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
The Huffman Encoding Project
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112