1.13k likes | 1.28k Views
Chapter 13. Priority Queues. 13.1 Introduction 13.2 The PurePriorityQueue Interface 13.3 Implementations of the PurePriorityQueue Interface 13.3.2 The Heap Implementation of the PurePriorityQueue Interface 13.4 Application: Huffman Codes.
E N D
Chapter 13 Priority Queues
13.1 Introduction 13.2 The PurePriorityQueue Interface 13.3 Implementations of the PurePriorityQueue Interface 13.3.2 The Heap Implementation of the PurePriorityQueue Interface 13.4 Application: Huffman Codes Chap.13 Contents
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. 13.1 Introduction
public interface PriorityQueue { /** * size回傳PurePriorityQueue中元素的個數 */ int size ( ) 13.2 The PurePriorityQueue Interface
/* isEmpty 看 PurePriorityQueue * 是否沒有元素. * * return true – if PurePriorityQueue * 沒有元素 ; * otherwise, return false ; */ boolean isEmpty ( )
/** * add加元素到 PurePriorityQueue . * * The worstTime(n) is O(n). * * @param element – 要插入PurePriorityQueue的元素 */ void add (E element)
/* getMin * 回傳 PurePriorityQueue 中的最高優先權元素 * * The worstTime(n) is O (1). * * @return PurePriorityQueue 的最高優先權元素 * * @throws NoSuchElementException – * if PurePriorityQueue 是空的 */ E getMin ( )
/* removeMin * 從PurePriorityQueue 移除具有最高優先權的元素 * * The worstTime(n) is O (log n). * * @return被移除的元素 * *@throws NoSuchElementException – * if PurePriorityQueue 是空的 */ E removeMin ( )
有三種 data structures 可實作之,分別是: 1) linked list 2) tree set 3) heap 13.3 Implementations of The PurePriorityQueue Interface
public class LinkedPQ <E> impelments PurePriorityQueue <E> { LinkedList <E> list ; Comparator <E> comparator ;
public LinkedPQ() {list = new LinkedList<E>( ) ; comparator = null ; } public LinkedPQ (Comparator<E> comp) {this() ; comparator = comp ;} public int size() { return list.size() ; } public E getMin() { return list.getFirst() ; } public E removeMin(){ return list.removeFirst() ;}
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<E> 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.
publicclass TreeSetPQ<E> implements PriorityQueue<E> { TreeSet<E> set; Comparator<E> comparator; // the 2 constructors, size, isEmpty and compare // methods 與LinkedPQ class的類似 public TreeSetPQ (Comparator<E> c) { comparator = c ; set = new TreeSet<E> (c); } // one-parameter constructor
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.
A collection of articles or mass of material gathered togetherin one place. 這定義用於 compiler, OS. Ex: Heap storage (堆) vs. stack storage (疊 ) in main memory. Heap [Collins English Dictionary]
但是, Data Structure中的 Heap, 有不同的定義: Heap 是一棵tree, 且任何一個節點比 所有descendants (後代) 都小
heap 不是 binary search tree! 因為對 root 而言 binary search tree 是 左小右大 heap 則是上(root)小下(左右)大 這叫 min heap (minimal element at root) 另有max heap (maximal element at root) 則是下(左右)小上(root) 大
下列的學生分數程式,創出 Heap結構 , 並執行 Heap 動作: add和 removeMin 請輸入學生姓名及GPA或***(結束)”; Mary 4.0 (red indicates user input) John 3.5 *** 系統輸出如下 John 3.5 Mary 4.0
publicstatic void main(String[] args){ final String PROMPT= “請輸入學生姓名及GPA或***(結束)”; final String RESULTS =“\n學生姓名及GPA如下” ; String line ; Heap<Student>heap = new Heap<Student>( ) ; 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
import java.util.* ; public class Student implements Comparable { protected String name ; protected double gpa ; /** Student 從特定的String s 初始化 Student object. * * @param s – String 初始化 Student object. *@throws 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
13.3.2 The Heap Implementation of the PurePriorityQueue Interface
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; //否則 swapparent 與 child temp=heap[parent];heap[parent]=heap[child];heap[child]=temp; /*child 向上走一步*/ child = parent; }//end while } //end of percolateUp
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