DataStruct 8. Heaps and Priority Queues

Size: px
Start display at page:

Download "DataStruct 8. Heaps and Priority Queues"

Transcription

1 DataStruct 8. Heaps and Priority Queues Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., November 13, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, College of Engineering, Yeungnam University, KOREA (Tel : ; Fax : ytkim@yu.ac.kr)

2 Priority Queue ADT Outline Implementing a Priority Queue with a List Heaps Implementing a Priority Queue with Heap based on Vector Complete Tree Adaptable Priority Queues DS 8-2

3 8.1 Priority Queue ADT A priority queue stores a collection of entries Typically, an entry is a pair (key, value), where the key indicates the priority Main methods of the Priority Queue ADT insert(e) : inserts an entry e removemin() : removes the entry with smallest key Additional methods min() : returns, but does not remove, an entry with smallest key size(), empty() Applications: Standby flyers Auctions Stock market DS 8-3

4 Total Order Relations Keys in a priority queue can be arbitrary objects on which an order is defined Two distinct entries in a priority queue can have the same key Mathematical concept of total order relation Reflexive property: x x Anti-symmetric property: x y y x x = y Transitive property: x y y z x z DS 8-4

5 Comparator ADT Implements the boolean function isless(p,q), which tests whether p < q Can derive other relations from this: (p == q) is equivalent to (!isless(p, q) &&!isless(q, p)) Can implement in C++ by overloading () Two ways to compare 2D points: class LeftRight { // left-right comparator public: bool operator()(const Point2D& p, const Point2D& q) const { return p.getx() < q.getx(); } }; class BottomTop { // bottom-top public: bool operator()(const Point2D& p, const Point2D& q) const { return p.gety() < q.gety(); } }; DS 8-5

6 Priority Queue ADT Functions supported in Priority Queue ADT size() empty() insert(e) min() removemin() Operation Output Priority Queue insert(5) - {5} insert(9) - {5, 9} insert(2) - {2, 5, 9} insert(7) - {2, 5, 7, 9} min() [2] {2, 5, 7, 9} removemin() - {5, 7, 9} size() 3 {5, 7, 9} min() [5] {5, 7, 9} removemin() - {7, 9} removemin() - {9} removemin() - {} empty() true {} removemin() error {} DS 8-6

7 C++ Priority Queue Interface informal PriorityQueue interface template <typename E, typename C> // element and comparator class PriorityQueue { // priority-queue interface public: int size() const; // number of elements bool isempty() const; // is the queue empty? void insert(const E& e); // insert element const E& min() const throw(queueempty); // minimum element void removemin() throw(queueempty); // remove minimum }; DS 8-7

8 Sorting with Priority Queue We can use a priority queue to sort a set of comparable elements 1. Insert the elements one by one with a series of insert operations 2. Remove the elements in sorted order with a series of removemin operations The running time of this sorting method depends on the priority queue implementation Algorithm PriorityQueueSort(L, P) Input STL list, L, of n elements and a priority queue, P, that compares elements using a total order relation Output The sorted list L while!l.empty () e L.front(); L.popFront() P.insert (e) while!p.empty() e P.min() P.removeMin() L.push_back(e) DS 8-8

9 STL Priority Queue Class Using STL Priority Queue Class #include <queue> using namespace std; priority_queue<int> priq_1; priority_queue<point2d, vector<point2d>, LeftRight> priq_2; Operations size() empty() push(e) top() pop() DS 8-9

10 8.2 Implementing a Priority Queue with a List class ListPriorityQueue (1) template <typename E, typename C> class ListPriorityQueue { public: int size() const; // number of elements bool empty() const; // is the queue empty? void insert(const E& e); // insert element const E& min() const; // minimum element void removemin(); // remove minimum private: std::list<e> L; // priority queue contents C isless; // less-than comparator }; DS 8-10

11 class ListPriorityQueue (2) template <typename E, typename C> // number of elements int ListPriorityQueue<E,C>::size() const { return L.size(); } template <typename E, typename C> // is the queue empty? bool ListPriorityQueue<E,C>::empty() const { return L.empty(); } template <typename E, typename C> // insert element void ListPriorityQueue<E,C>::insert(const E& e) { typename std::list<e>::iterator p; p = L.begin(); while (p!= L.end() &&!isless(e, *p)) ++p; // find element that is larger than e L.insert(p, e); // insert e before p } template <typename E, typename C> // minimum element const E& ListPriorityQueue<E,C>::min() const { return L.front(); } // minimum is at the front template <typename E, typename C> // remove minimum void ListPriorityQueue<E,C>::removeMin() { L.pop_front(); } DS 8-11

12 Selection-Sort Selection-sort is the variation of PQ-sort where the priority queue is implemented with an unsorted sequence Running time of Selection-sort: 1. Inserting the elements into the priority queue with n insert operations takes O(n) time 2. Removing the elements in sorted order from the priority queue with n removemin() operations takes time proportional to n + (n 1) Selection-sort runs in O(n 2 ) time DS 8-12

13 Selection-Sort Example List L Priority Queue P Input: (7,4,8,2,5,3,9) () Phase 1 (a) (4,8,2,5,3,9) (7) (b) (8,2,5,3,9) (7,4) (g) () (7,4,8,2,5,3,9) Phase 2 (a) (2) (7,4,8,5,3,9) (b) (2,3) (7,4,8,5,9) (c) (2,3,4) (7,8,5,9) (d) (2,3,4,5) (7,8,9) (e) (2,3,4,5,7) (8,9) (f) (2,3,4,5,7,8) (9) (g) (2,3,4,5,7,8,9) () DS 8-13

14 Insertion-Sort Insertion-sort is the variation of PQ-sort where the priority queue is implemented with a sorted sequence Running time of Insertion-sort: 1. Inserting the elements into the priority queue with n insert operations takes time proportional to n 2. Removing the elements in sorted order from the priority queue with a series of n removemin() operations takes O(n) time Insertion-sort runs in O(n 2 ) time DS 8-14

15 Insertion-Sort Example List L Priority queue P Input: (7,4,8,2,5,3,9) () Phase 1 (a) (4,8,2,5,3,9) (7) (b) (8,2,5,3,9) (4,7) (c) (2,5,3,9) (4,7,8) (d) (5,3,9) (2,4,7,8) (e) (3,9) (2,4,5,7,8) (f) (9) (2,3,4,5,7,8) (g) () (2,3,4,5,7,8,9) Phase 2 (a) (2) (3,4,5,7,8,9) (b) (2,3) (4,5,7,8,9) (g) (2,3,4,5,7,8,9) () DS 8-15

16 In-place Insertion-Sort Instead of using an external data structure, we can implement selectionsort and insertion-sort inplace A portion of the input sequence itself serves as the priority queue For in-place insertion-sort We keep sorted the initial portion of the sequence We can use swaps instead of modifying the sequence DS 8-16

17 Recall Priority Queue ADT A priority queue stores a collection of entries Typically, an entry is a pair (key, value), where the key indicates the priority Main methods of the Priority Queue ADT insert(e) : inserts an entry e removemin() : removes the entry with smallest key Additional methods min() : returns, but does not remove, an entry with smallest key size(), empty() Applications: Standby flyers Auctions Stock market DS 8-17

18 Recall PQ Sorting We use a priority queue Insert the elements with a series of insert operations Remove the elements in sorted order with a series of removemin operations The running time depends on the priority queue implementation: Unsorted sequence gives selection-sort: O(n 2 ) time Sorted sequence gives insertion-sort: O(n 2 ) time Can we do better? DS 8-18

19 8.3 Heaps A heap is a binary tree storing keys at its nodes and satisfying the following properties: Heap-Order: for every internal node v other than the root, key(v) key(parent(v)) Complete Binary Tree: let h be the height of the heap for i = 0,, h 1, there are 2 i nodes of depth i at depth h 1, the internal nodes are to the left of the external nodes The last node of a heap is the rightmost node of maximum depth last node DS 8-19

20 Complete Binary Tree Complete Binary Tree Property a heap T with height h is a complete binary tree, that is, levels 0, 1, 2,, h-1 of T have the maximum number of nodes possible (namely, level i has 2 i nodes, for 0 i h-1 ) and nodes at level h fill this level from left to right DS 8-20

21 Vector Representation of a Complete Binary Tree Vector representation of a complete binary tree if v is the root of T, then f(v) = 1 if v is the left child of node u, then f(v) = 2 f(u) if v is the right child of node u, then f(v) = 2 f(u) + 1 DS 8-21

22 Vector-based Heap Implementation We can represent a heap with n keys by means of a vector of length n + 1 For the node at rank i the left child is at rank 2i the right child is at rank 2i + 1 Links between nodes are not explicitly stored The cell of at rank 0 is not used Operation insert() corresponds to inserting at rank n + 1 Operation removemin() corresponds to removing at rank n Yields in-place heap-sort DS 8-22

23 Height of a Heap Theorem: A heap storing n keys has height O(log n) Proof: (we apply the complete binary tree property) Let h be the height of a heap storing n keys Since there are 2 i keys at depth i = 0,, h 1 and at least one key at depth h, we have n h Thus, n 2 h, i.e., h log n depth 0 1 h 1 h keys h 1 1 DS 8-23

24 C++ implementation of a Complete Binary Tree class VectorCompleteTree (1) template <typename E> class VectorCompleteTree { // private member data and protected utilities private: // member data std::vector<e> V; // tree contents public: // publicly accessible types typedef typename std::vector<e>::iterator Position; // a position in the tree protected: // protected utility functions Position pos(int i) // map an index to a position { return V.begin() + i; } int idx(const Position& p) const // map a position to an index { return p - V.begin(); } DS 8-24

25 class VectorCompleteTree (2) public: VectorCompleteTree() : V(1) {} // constructor, insert dummy data at index 0 int size() const { return V.size() - 1; } Position left(const Position& p) { return pos(2*idx(p)); } Position right(const Position& p) { return pos(2*idx(p) + 1); } Position parent(const Position& p) { return pos(idx(p)/2); } bool hasleft(const Position& p) const { return 2*idx(p) <= size(); } bool hasright(const Position& p) const { return 2*idx(p) + 1 <= size(); } bool isroot(const Position& p) const { return idx(p) == 1; } Position root() { return pos(1); } Position last() { return pos(size()); } void addlast(const E& e) { V.push_back(e); } void removelast() { V.pop_back(); } void swap(const Position& p, const Position& q) { E e = *q; *q = *p; *p = e; } }; DS 8-25

26 Heaps and Priority Queues We can use a heap to implement a priority queue We store a (key, element) item at each internal node We keep track of the position of the last node (2, Sue) (5, Pat) (6, Mark) (9, Jeff) (7, Anna) last node DS 8-26

27 Insertion into a Heap Method insertitem of the priority queue ADT corresponds to the insertion of a key k to the heap The insertion algorithm consists of three steps Find the insertion node z (the new last node) Store k at z Restore the heap-order property (discussed next) z 6 insertion node z 6 DS 8-27

28 Upheap After the insertion of a new key k, the heap-order property may be violated Algorithm upheap restores the heap-order property by swapping k along an upward path from the insertion node Upheap terminates when the key k reaches the root or a node whose parent has a key smaller than or equal to k Since a heap has height O(log n), upheap runs in O(log n) time z 1 5 z DS 8-28

29 Insertion with up-heap bubbling (1) DS 8-29

30 Insertion with up-heap bubbling (2) DS 8-30

31 Insertion with up-heap bubbling (3) DS 8-31

32 Removal from a Heap Method removemin of the priority queue ADT corresponds to the removal of the root key from the heap w 2 6 The removal algorithm consists of three steps last node Replace the root key with the key of the last node w 7 Remove w Restore the heap-order property (discussed next) 9 5 w 6 new last node DS 8-32

33 Downheap After replacing the root key with the key k of the last node, the heap-order property may be violated Algorithm downheap restores the heap-order property by swapping key k along a downward path from the root Downheap terminates when key k reaches a leaf or a node whose children have keys greater than or equal to k Since a heap has height O(log n), downheap runs in O(log n) time w w 6 DS 8-33

34 Down-heap Bubbling after a Removal (1) DS 8-34

35 Down-heap Bubbling after a Removal (2) DS 8-35

36 C++ implementation of HeapPriorityQueue HeapPriorityQueue for OS Task Scheduling (1) /** Task.h */ #ifndef TASK_H #define TASK_H #include <iostream> #include <string> using namespace std; class Task { friend ostream& operator<<(ostream&, const Task&); public: Task(); // constructor Task(string tname, int pri, int dur); string gettaskname() {return taskname;} int getpriority() { return priority;} int getduration() { return duration;} void settaskname(string n) { taskname = n;} void setpriority(int); void setduration(int); bool operator>(task& t) { return (priority > t.priority);} bool operator<(task& t) { return (priority < t.priority);} private: string taskname; // name of task int priority; // priority of task in scheduling: 0 ~ 49 int duration; // duration of processing time, [ms] }; #endif DS 8-36

37 HeapPriorityQueue for OS Task Scheduling (2) /** Task.cpp */ #include <iostream> #include "Task.h" using namespace std; Task::Task() { } Task::Task(string tname, int pri, int dur) { taskname = tname; setpriority(pri); setduration(dur); } void Task::setPriority(int pri) { if (pri >= 0 && pri <50) priority = pri; else priority = 49; } DS 8-37

38 HeapPriorityQueue for OS Task Scheduling (3) /** Task.cpp (2) */ void Task::setDuration(int dur) { if (dur > 0 && dur <100) duration = dur; else duration = 1; } ostream& operator<<(ostream& fout, const Task& t) { fout <<"Task - name (" << t.taskname; fout << "), pri (" << t.priority << "), duration (" << t.duration; fout << ")"; } return fout; DS 8-38

39 HeapPriorityQueue for OS Task Scheduling (4) /** VectorCompleteTree.h (1) */ #ifndef VECTORCOMPLETETREE_H #define VECTORCOMPLETETREE_H #include <iostream> #include <vector> #include "Task.h" using namespace std; typedef std::vector<task>::iterator Position; class VectorCompleteTree { private: std::vector<task> V; public: protected: Position pos(int i) {return V.begin() + i; } int idx(const Position& p) const { return p - V.begin(); } DS 8-39

40 HeapPriorityQueue for OS Task Scheduling (5) /** VectorCompleteTree.h (2) */ public: private: }; VectorCompleteTree() : V(1) {} int size() const {return V.size() - 1;} Position left(const Position& p) { return pos(2 * idx(p));} Position right(const Position& p) { return pos(2 * idx(p)) + 1;} Position parent(const Position& p) { return pos(idx(p) / 2); } bool hasleft(const Position& p) const { return (2*idx(p) <= size()); } bool hasright(const Position& p) const { return (2*idx(p) + 1 <= size()); } bool isroot(const Position& p) const { return idx(p) == 1; } Position getroot() {return pos(1); } Position getlast() {return pos(size());} void addlast(const Task& enode) { V.push_back(eNode); numtn++;} void removelast() {V.pop_back();numTN--;} void swap(const Position& p, const Position& q) { Task e = *q; *q = *p; *p = e;} void printvectorcompletetreebylevel(position p, int level); int numtn; #endif DS 8-40

41 HeapPriorityQueue for OS Task Scheduling (6) /** VectorCompleteTree.cpp */ #include "VectorCompleteTree.h" #include "Task.h" using namespace std; void VectorCompleteTree::printVectorCompleteTreeByLevel(Position p, int level) { Position poschild; if (level == 0) cout << "\ nroot (data: "; cout <<*p; cout << ")" << endl; for (int i=0; i<level; i++) cout << " "; if (hasleft(p)) { poschild = left(p); cout << "L (data: "; printvectorcompletetreebylevel(poschild, level+1); } else { cout << "L (NULL)" << endl; } DS 8-41

42 HeapPriorityQueue for OS Task Scheduling (7) /** VectorCompleteTree.cpp (2) */ for (int i=0; i<level; i++) cout << " "; if (hasright(p)) { poschild = right(p); } else { } cout << "R (data: "; printvectorcompletetreebylevel(poschild, level+1); cout << "R (NULL)" << endl; } DS 8-42

43 HeapPriorityQueue for OS Task Scheduling (8) /** HeapPriorityQueue.h */ #ifndef HEAPPRIORITYQUEUE_H #define HEAPPRIORITYQUEUE_H #include <iostream> #include "VectorCompleteTree.h" #include "Task.h" using namespace std; class HeapPriorityQueue { public: //HeapPriorityQueue(); int size() const; bool empty() const; void insert(const Task& ele); const Task& min(); void removemin(); VectorCompleteTree* getvctree() {return &vctree;} private: VectorCompleteTree vctree; }; #endif DS 8-43

44 HeapPriorityQueue for OS Task Scheduling (9) /** HeapPriorityQueue.cpp (1) */ #include "HeapPriorityQueue.h" #include "Task.h" int HeapPriorityQueue::size() const { return vctree.size(); } bool HeapPriorityQueue::empty() const { return size() == 0; } const Task& HeapPriorityQueue::min() { return *(vctree.getroot()); } void HeapPriorityQueue::insert(const Task& e) { vctree.addlast(e); Position v = vctree.getlast(); while (!vctree.isroot(v)) { Position u = vctree.parent(v); if (*v > *u) break; vctree.swap(v, u); v = u; } } DS 8-44

45 HeapPriorityQueue for OS Task Scheduling (10) /** HeapPriorityQueue.cpp (2) */ void HeapPriorityQueue::removeMin() { if (size() == 1) vctree.removelast(); else { Position u = vctree.getroot(); Position z = vctree.getlast(); vctree.swap(u, z); vctree.removelast(); while (vctree.hasleft(u)) { Position v = vctree.left(u); Position w = vctree.right(u); if (vctree.hasright(u) && (*v > *w)) v = w; if (*v < *u) { vctree.swap(u, v); u = v; } else break; } } } DS 8-45

46 HeapPriorityQueue for OS Task Scheduling (11) /** main.cpp (1) */ #include <iostream> #include <string> #include <stdlib.h> #include "Task.h" #include "VectorCompleteTree.h" #include "HeapPriorityQueue.h" #include "Task.h" using namespace std; void main() { string tname = ""; char tmp[10]; int priority = -1; int duration = 0; Task* ptask; HeapPriorityQueue taskheappriq; VectorCompleteTree* pvct = taskheappriq.getvctree(); DS 8-46

47 HeapPriorityQueue for OS Task Scheduling (12) /** main.cpp (2) */ for (int i=10; i>0; i--) { _itoa_s(i, tmp, 10); tname = "task_" + string(tmp); priority = i; duration = i; ptask = new Task(tName, priority, duration); taskheappriq.insert(*ptask); cout << "\ nsize of task Heap Priority Queue (after insertion of task ( ; cout << tname << ", " << priority << ", " << duration <<") : ; cout << taskheappriq.size() << endl; cout << "Heap Priority Queue Architecture: " << endl; pvct->printvectorcompletetreebylevel(pvct->getroot(), 0); cout << endl; } for (int i=0; i<10; i++) { cout << "Top priority task in Heap Priority Queue : " << taskheappriq.min(); cout << endl; cout << " removemin()... "; taskheappriq.removemin(); cout << ", size after removemin(): " << taskheappriq.size() << endl; } } // end main(); DS 8-47

48 HeapPriorityQueue for OS Task Scheduling (13) DS 8-48

49 HeapPriorityQueue for OS Task Scheduling (14) DS 8-49

50 Heap-Sort Consider a priority queue with n items implemented by means of a heap the space used is O(n) methods insert and removemin take O(log n) time methods size, empty, and min take time O(1) time Using a heap-based priority queue, we can sort a sequence of n elements in O(n log n) time The resulting algorithm is called heap-sort Heap-sort is much faster than quadratic sorting algorithms, such as insertion-sort and selection-sort DS 8-50

51 8.4 Adaptable Priority Queues Methods of the Adaptable Priority Queue ADT insert(e): Insert the entry e into PQ and return a position referring to this entry remove(p): Remove from PQ the entry referenced by position p replace(p, e): Replace with e the element associated with the entry referenced by p and return the position of the altered entry Locating Entries In order to implement the operations remove(p) and replace(p, e), and we need fast ways of locating an entry p in a priority queue (PQ) DS 8-51

52 List-based Implementation A location-aware list entry is an object storing key value position (or rank) of the item (entry, e) in the list In turn, the position (or array cell) stores the entry Back pointers (or ranks) are updated during swaps header nodes/positions trailer 2 B 4 D 5 E 8 H entries DS 8-52

53 Adaptable Priority Queue (1) template <typename E, typename C> class AdaptPriorityQueue { // adaptable priority queue protected: typedef std::list<e> ElementList; // list of elements public: // Position class definition class Position { // a position in the queue private: typename ElementList::iterator q; // a position in the list public: const E& operator*() { return *q; } // the element at this position friend class AdaptPriorityQueue; // grant access }; public: int size() const; // number of elements bool empty() const; // is the queue empty? const E& min() const; // minimum element Position insert(const E& e); // insert element void removemin(); // remove minimum void remove(const Position& p); // remove at position p Position replace(const Position& p, const E& e); // replace at position p DS 8-53

54 Adaptable Priority Queue (2) // class AdaptPriorityQueue (continued...) private: ElementList L; C isless; }; // priority queue contents // less-than comparator template <typename E, typename C> typename AdaptPriorityQueue<E,C>::Position AdaptPriorityQueue<E,C>::insert(const E& e) { typename ElementList::iterator p = L.begin(); while (p!= L.end() &&!isless(e, *p)) ++p; L.insert(p, e); Position pos; pos.q = --p; return pos; } // insert element // find larger element // insert before p // inserted position DS 8-54

55 Adaptable Priority Queue (3) template <typename E, typename C> // remove at position p void AdaptPriorityQueue<E,C>::remove(const Position& p) { L.erase(p.q); } template <typename E, typename C> // replace at position p typename AdaptPriorityQueue<E,C>::Position AdaptPriorityQueue<E,C>::replace(const Position& p, const E& e) { L.erase(p.q); // remove the old entry return insert(e); // insert replacement } DS 8-55

56 Location-Aware Entries A locator-aware entry identifies and tracks the location of its (key, value) object within a data structure Intuitive notion: Coat claim check Valet claim ticket Reservation number Main idea: Since entries are created and returned from the data structure itself, it can return location-aware entries, thereby making future updates easier DS 8-56

57 Homework DS-8 DS-8.1 Projects P-8.3 (Priority queue based on heap) DS-8.2 Projects P-8.4 (in-place heap-sort algorithm) DS-8.3 Projects P-8.7 (Priority queue for job scheduling) DS 8-57

Heaps 2. Recall Priority Queue ADT. Heaps 3/19/14

Heaps 2. Recall Priority Queue ADT. Heaps 3/19/14 Heaps 3// Presentation for use with the textbook Data Structures and Algorithms in Java, th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 0 Heaps Heaps Recall Priority Queue ADT

More information

Heaps Goodrich, Tamassia. Heaps 1

Heaps Goodrich, Tamassia. Heaps 1 Heaps Heaps 1 Recall Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue ADT insert(k, x) inserts an entry with key k

More information

CH 8. HEAPS AND PRIORITY QUEUES

CH 8. HEAPS AND PRIORITY QUEUES CH 8. HEAPS AND PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

Priority Queues. Outline. COMP9024: Data Structures and Algorithms. Priority Queue ADT. Total Order Relations. Entry ADT

Priority Queues. Outline. COMP9024: Data Structures and Algorithms. Priority Queue ADT. Total Order Relations. Entry ADT COMP0: Data Structures and Algorithms Week Seven: Priority Queues Hui Wu Outline Priority Queues Heaps Adaptable Priority Queues Session, 0 http://www.cse.unsw.edu.au/~cs0 Priority Queue ADT Priority Queues

More information

CH. 8 PRIORITY QUEUES AND HEAPS

CH. 8 PRIORITY QUEUES AND HEAPS CH. 8 PRIORITY QUEUES AND HEAPS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

Data Structures and Algorithms " Priority Queues!

Data Structures and Algorithms  Priority Queues! Data Structures and Algorithms " Priority Queues! Outline" Priority Queues! Heaps! Adaptable Priority Queues! Priority Queues" Priority Queue ADT" A priority queue stores a collection of entries! Each

More information

Priority Queues and Heaps. Heaps and Priority Queues 1

Priority Queues and Heaps. Heaps and Priority Queues 1 Priority Queues and Heaps 2 5 6 9 7 Heaps and Priority Queues 1 Priority Queue ADT A priority queue stores a collection of items An item is a pair (key, element) Main methods of the Priority Queue ADT

More information

Stores a collection of elements each with an associated key value

Stores a collection of elements each with an associated key value CH9. PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 201) PRIORITY QUEUES Stores a collection

More information

Heaps. 2/13/2006 Heaps 1

Heaps. 2/13/2006 Heaps 1 Heaps /13/00 Heaps 1 Outline and Reading What is a heap ( 8.3.1) Height of a heap ( 8.3.) Insertion ( 8.3.3) Removal ( 8.3.3) Heap-sort ( 8.3.) Arraylist-based implementation ( 8.3.) Bottom-up construction

More information

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES 2 5 6 9 7 Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H., Wiley, 2014

More information

Heaps and Priority Queues

Heaps and Priority Queues Heaps and Priority Queues Lecture delivered by: Venkatanatha Sarma Y Assistant Professor MSRSAS-Bangalore 11 Objectives To introduce Priority Queue ADT To discuss and illustrate Priority Queues for sorting

More information

Priority Queue ADT ( 7.1) Heaps and Priority Queues 2. Comparator ADT ( 7.1.4) Total Order Relation. Using Comparators in C++

Priority Queue ADT ( 7.1) Heaps and Priority Queues 2. Comparator ADT ( 7.1.4) Total Order Relation. Using Comparators in C++ Heaps and Priority Queues Priority Queue ADT (.) A priority queue stores a collection of items An item is a pair (key, element) Main methods of the Priority Queue ADT insertitem(k, o) inserts an item ith

More information

CSED233: Data Structures (2017F) Lecture9: Priority Queues and Heaps

CSED233: Data Structures (2017F) Lecture9: Priority Queues and Heaps (2017F) Lecture9: Priority Queues and Heaps Daijin Kim CSE, POSTECH dkim@postech.ac.kr Priority Queue ADT A priority queue stores a coll ection of entries Each entry is a pair (key, value) Main methods

More information

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods 1 2 Given : Stack A, Stack B 3 // based on requirement b will be reverse of

More information

Data Structures Lecture 7

Data Structures Lecture 7 Fall 2017 Fang Yu Software Security Lab. Dept. Management Information Systems, National Chengchi University Data Structures Lecture 7 Recap We have talked about object oriented programing Chapter 1, 2,

More information

Priority Queues & Heaps. Chapter 9

Priority Queues & Heaps. Chapter 9 Priority Queues & Heaps Chapter 9 The Java Collections Framework (Ordered Data Types) Interface Abstract Class Class Iterable Collection Queue Abstract Collection List Abstract Queue Abstract List Priority

More information

DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries

DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries 2013-2 DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 22, 2013 Advanced

More information

Priority Queues and Heaps. More Data Structures. Priority Queue ADT ( 2.4.1) Total Order Relation. Sorting with a Priority Queue ( 2.4.

Priority Queues and Heaps. More Data Structures. Priority Queue ADT ( 2.4.1) Total Order Relation. Sorting with a Priority Queue ( 2.4. More Data Structures Priority Queues and Heaps Priority Queues, Comparators, Locators, Dictionaries More Data Structures v. More Data Structures v. Priority Queue ADT (.4.) Total Order Relation A priority

More information

Sorting. Outline. Sorting with a priority queue Selection-sort Insertion-sort Heap Sort Quick Sort

Sorting. Outline. Sorting with a priority queue Selection-sort Insertion-sort Heap Sort Quick Sort Sorting Hiroaki Kobayashi 1 Outline Sorting with a priority queue Selection-sort Insertion-sort Heap Sort Quick Sort Merge Sort Lower Bound on Comparison-Based Sorting Bucket Sort and Radix Sort Hiroaki

More information

Data Structures and Algorithms

Data Structures and Algorithms Berner Fachhochschule - Technik und Informatik Data Structures and Algorithms Heaps and Priority Queues Philipp Locher FS 2018 Heaps and Priority Queues Page 1 Outline Heaps Heap-Sort Priority Queues Heaps

More information

Algorithms and Data Structures

Algorithms and Data Structures Priority Queues and Heaps Page 1 BFH-TI: Softwareschule Schweiz Priority Queues and Heaps Dr. CAS SD01 Priority Queues and Heaps Page 2 Outline Priority Queues Heaps Heap-Based Priority Queues Priority

More information

Priority Queues. Reading: 7.1, 7.2

Priority Queues. Reading: 7.1, 7.2 Priority Queues Reading: 7.1, 7.2 Generalized sorting Sometimes we need to sort but The data type is not easily mapped onto data we can compare (numbers, strings, etc) The sorting criteria changes depending

More information

Priority queues. Priority queues. Priority queue operations

Priority queues. Priority queues. Priority queue operations Priority queues March 30, 018 1 Priority queues The ADT priority queue stores arbitrary objects with priorities. An object with the highest priority gets served first. Objects with priorities are defined

More information

Elementary Data Structures 2

Elementary Data Structures 2 Elementary Data Structures Priority Queues, & Dictionaries Priority Queues Sell 00 IBM $ Sell 300 IBM $0 Buy 00 IBM $9 Buy 400 IBM $8 Priority Queue ADT A priority queue stores a collection of items An

More information

Chapter 2: Basic Data Structures

Chapter 2: Basic Data Structures Chapter 2: Basic Data Structures Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority Queues and Heaps Dictionaries and Hash Tables Spring 2014 CS 315 2 Two

More information

Priority queues. Priority queues. Priority queue operations

Priority queues. Priority queues. Priority queue operations Priority queues March 8, 08 Priority queues The ADT priority queue stores arbitrary objects with priorities. An object with the highest priority gets served first. Objects with priorities are defined by

More information

Entry and Priority Queue ADTs

Entry and Priority Queue ADTs Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Adaptable Priority Queues 3 a 5 g 4 e Adaptable

More information

1/27/2005 2:03 AM Priority Queues 1. Outline and Reading

1/27/2005 2:03 AM Priority Queues 1. Outline and Reading Priority Queues Sell 100 $122 Sell 300 $120 Buy 500 $119 Buy 400 $118 Priority Queues 1 Outline and Reading PriorityQueue ADT ( 2.4.1) Total order relation ( 2.4.1) Comparator ADT ( 2.4.1) Sorting with

More information

Priority Queues 3/19/14

Priority Queues 3/19/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Priority Queues Priority Queues 1 Priority

More information

Heaps Outline and Required Reading: Heaps ( 7.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Heaps Outline and Required Reading: Heaps ( 7.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic 1 Heaps Outline and Required Reading: Heaps (.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic Heap ADT 2 Heap binary tree (T) that stores a collection of keys at its internal nodes and satisfies

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 12: Heaps and Priority Queues MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Heaps and Priority Queues 2 Priority Queues Heaps Priority Queue 3 QueueADT Objects are added and

More information

Containers: Priority Queues. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Priority Queues. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Priority Queues Jordi Cortadella and Jordi Petit Department of Computer Science A priority queue A priority queue is a queue in which each element has a priority. Elements with higher priority

More information

Containers: Priority Queues

Containers: Priority Queues A priority queue Containers: Priority Queues A priority queue is a queue in which each element has a priority. Elements with higher priority are served before elements with lower priority. It can be implemented

More information

Priority Queues & Heaps. CS16: Introduction to Data Structures & Algorithms Spring 2019

Priority Queues & Heaps. CS16: Introduction to Data Structures & Algorithms Spring 2019 Priority Queues & Heaps CS16: Introduction to Data Structures & Algorithms Spring 2019 Outline Priority Queues Motivation ADT Implementation Heaps insert( ) and upheap( ) removemin( ) and downheap( ) Motivation

More information

DataStruct 7. Trees. Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011.

DataStruct 7. Trees. Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. 2013-2 DataStruct 7. Trees Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 6, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept.

More information

Priority Queues Goodrich, Tamassia. Priority Queues 1

Priority Queues Goodrich, Tamassia. Priority Queues 1 Priority Queues Priority Queues 1 Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue ADT insert(k, x) inserts an entry

More information

Height of a Heap. Heaps. 1. Insertion into a Heap. Heaps and Priority Queues. The insertion algorithm consists of three steps

Height of a Heap. Heaps. 1. Insertion into a Heap. Heaps and Priority Queues. The insertion algorithm consists of three steps Heaps A heap is a binary tree storing keys at its nodes and satisfying the folloing properties:! Heap-Order: " for every internal node v other than the root, key(v)! key(parent(v))! Complete Binary Tree:

More information

Heaps, Heap Sort, and Priority Queues.

Heaps, Heap Sort, and Priority Queues. Heaps, Heap Sort, and Priority Queues Sorting III / Slide 2 Background: Binary Trees Has a root at the topmost level Each node has zero, one or two children A node that has no child is called a leaf For

More information

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley CSCI 04 Binary Trees / Priority Queues / Heaps Mark Redekopp Michael Crowley Trees Definition: A connected, acyclic (no cycles) graph with: A root node, r, that has 0 or more subtrees Exactly one path

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 10: Search and Heaps MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Search and Heaps 2 Linear Search Binary Search Introduction to trees Priority Queues Heaps Linear Search

More information

In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories 9 1

In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories 9 1 What is a Tree Trees Stock Fraud Make Money Fast! Winning Lotto / Bank Robbery In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes ith a parent-child relation

More information

Topics on the Midterm

Topics on the Midterm Midterm Review Topics on the Midterm Data Structures & Object-Oriented Design Run-Time Analysis Linear Data Structures The Java Collections Framework Recursion Trees Priority Queues & Heaps Maps, Hash

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Spring 2017-2018 Outline 1 Priority Queues Outline Priority Queues 1 Priority Queues Jumping the Queue Priority Queues In normal queue, the mode of selection is first in,

More information

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue Priority Queues (0F) Lecture: Heaps Bohyung Han CSE, POSTECH bhhan@postech.ac.kr Queues Stores items (keys) in a linear list or array FIFO (First In First Out) Stored items do not have priorities. Priority

More information

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 20, March 24, 2016

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 20, March 24, 2016 Winter 201 COMP-250: Introduction to Computer Science Lecture 20, March 2, 201 Public Announcement Public Announcement In order to have your exam printed by the Exam Office, it must be submitted by: Course

More information

Priority Queues (Heaps)

Priority Queues (Heaps) Priority Queues (Heaps) 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the

More information

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010 CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010 Question 1 Part 1, Program A: This program reads integers on standard input and stops when it encounters EOF or a non-integer. It

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 13 (Based on Paul Kube course materials) CSE 100 Priority Queues in Huffman s algorithm Heaps and Priority Queues Time and space costs of coding with Huffman codes

More information

The smallest element is the first one removed. (You could also define a largest-first-out priority queue)

The smallest element is the first one removed. (You could also define a largest-first-out priority queue) Priority Queues Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The smallest element is the first one removed (You could also define a largest-first-out

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills CSCI 136 Data Structures & Advanced Programming Lecture 22 Fall 2018 Instructor: Bills Last Time Lab 7: Two Towers Array Representations of (Binary) Trees Application: Huffman Encoding 2 Today Improving

More information

Ch 8. Operator Overloading, Friends, and References

Ch 8. Operator Overloading, Friends, and References 2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel

More information

Priority Queues (Heaps)

Priority Queues (Heaps) Priority Queues (Heaps) October 11, 2016 CMPE 250 Priority Queues October 11, 2016 1 / 29 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full

More information

CS 315 April 1. Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin. algoritms for decrasekey increasekey Build-heap

CS 315 April 1. Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin. algoritms for decrasekey increasekey Build-heap CS 315 April 1 Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin percolate-down algoritms for decrasekey increasekey Build-heap heap-sorting, machine scheduling application Binary

More information

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater CS61B, Summer 2002 Lecture #8 Barath Raghavan UC Berkeley Topics: Binary Search Trees, Priority queues 1 Binary search trees (BSTs) Represented as ordinary binary trees Maintain binary search tree property

More information

9.2 Hash Tables. When implementing a map with a hash table, the goal is to store item (k, e) at index i = h(k)

9.2 Hash Tables. When implementing a map with a hash table, the goal is to store item (k, e) at index i = h(k) 9.2 Hash Tables A hash function h() maps keys of a given type to integers in a fixed interval [0, N - 1] Example: h(x) = x mod N is a hash function for integer keys The integer h(x) is called the hash

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Priority Queues and Huffman Trees

Priority Queues and Huffman Trees Priority Queues and Huffman Trees 1 the Heap storing the heap with a vector deleting from the heap 2 Binary Search Trees sorting integer numbers deleting from a binary search tree 3 Huffman Trees encoding

More information

CSCI Trees. Mark Redekopp David Kempe

CSCI Trees. Mark Redekopp David Kempe CSCI 104 2-3 Trees Mark Redekopp David Kempe Trees & Maps/Sets C++ STL "maps" and "sets" use binary search trees internally to store their keys (and values) that can grow or contract as needed This allows

More information

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments Heaps 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the one with the current

More information

10/1/2018 Data Structure & Algorithm. Circularly Linked List Doubly Linked List Priority queues Heaps

10/1/2018 Data Structure & Algorithm. Circularly Linked List Doubly Linked List Priority queues Heaps 10/1/2018 Data Structure & Algorithm Circularly Linked List Doubly Linked List Priority queues Heaps 1 Linked list: Head and Tail NULL Element Next 1. Head 2. Tail 3. Size 2 Make SinglyLinkedList implements

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Priority Queues. INFO0902 Data Structures and Algorithms. Priority Queues (files à priorités) Keys. Priority Queues

Priority Queues. INFO0902 Data Structures and Algorithms. Priority Queues (files à priorités) Keys. Priority Queues Priority Queues INFO0902 Data Structures and Algorithms Priority Queues Justus H. Piater Priority Queues (files à priorités) Keys Extract the top-priority element at any time. No notion of order, positions,

More information

Expression Trees and the Heap

Expression Trees and the Heap Expression Trees and the Heap 1 Binary Expression Trees evaluating expressions splitting strings in operators and operands 2 C++ Binary Tree of Strings header files defining the methods 3 the Heap or Priority

More information

csci 210: Data Structures Priority Queues and Heaps

csci 210: Data Structures Priority Queues and Heaps csci 210: Data Structures Priority Queues and Heaps Summary Topics the Priority Queue ADT Priority Queue vs Dictionary and Queues implementation of PQueue linked lists binary search trees heaps Heaps READING:

More information

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience) Binary heap data structure Heaps A binary heap is a special kind of binary tree - has a restricted structure (must be complete) - has an ordering property (parent value is smaller than child values) Used

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Lecture 2: Priority Queues, Heaps, and Heapsort Lecture 2: Priority Queues, Heaps, and Heapsort Sorting and Searching 1 / 24 Priority Queue: Motivating Example 3 jobs have been submitted

More information

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT Heaps Definition of a heap What are they for: priority queues Insertion and deletion into heaps Implementation of heaps Heap sort Not to be confused with: heap as the portion of computer memory available

More information

Algorithms and Theory of Computation. Lecture 7: Priority Queue

Algorithms and Theory of Computation. Lecture 7: Priority Queue Algorithms and Theory of Computation Lecture 7: Priority Queue Xiaohui Bei MAS 714 September 5, 2017 Nanyang Technological University MAS 714 September 5, 2017 1 / 15 Priority Queues Priority Queues Store

More information

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748 Data Structures Giri Narasimhan Office: ECS 254A Phone: x-3748 giri@cs.fiu.edu Motivation u Many applications where Items have associated priorities Job scheduling Long print jobs vs short ones; OS jobs

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Lecture 2: Priority Queues, Heaps, and Heapsort Lecture 2: Priority Queues, Heaps, and Heapsort Sorting and Searching 1 / 24 Priority Queue: Motivating Example 3 jobs have been submitted

More information

H.O.#12 Fall 2015 Gary Chan. Binary Tree (N:12)

H.O.#12 Fall 2015 Gary Chan. Binary Tree (N:12) H.O.#12 Fall 2015 Gary Chan Binary Tree (N:12) Outline Binary tree terminology Tree traversals: preorder, inorder and postorder Dictionary and binary search tree Binary search tree operations Search min

More information

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues INFO1x05 Tutorial 6 Heaps and Priority Queues Exercise 1: 1. How long would it take to remove the log n smallest elements from a heap that contains n entries, using the operation? 2. Suppose you label

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 2 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, 6.1 6.3 Izmir University of Economics 1 A kind of queue Priority Queue (Heap) Dequeue gets element with the

More information

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II Review from Lecture 22 CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II Using STL s for_each, Function Objects, a.k.a., Functors STL s unordered_set (and unordered_map) Hash functions

More information

CMSC 341 Lecture 14: Priority Queues, Heaps

CMSC 341 Lecture 14: Priority Queues, Heaps CMSC 341 Lecture 14: Priority Queues, Heaps Prof. John Park Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues:

More information

Tables, Priority Queues, Heaps

Tables, Priority Queues, Heaps Tables, Priority Queues, Heaps Table ADT purpose, implementations Priority Queue ADT variation on Table ADT Heaps purpose, implementation heapsort EECS 268 Programming II 1 Table ADT A table in generic

More information

Module 2: Priority Queues

Module 2: Priority Queues Module 2: Priority Queues CS 240 Data Structures and Data Management T. Biedl K. Lanctot M. Sepehri S. Wild Based on lecture notes by many previous cs240 instructors David R. Cheriton School of Computer

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Heaps Kostas Alexis The ADT Heap A heap is a complete binary tree that is either: Empty or Whose root contains a value >= each of its children and has heaps as

More information

COMP250: Priority queue ADT, Heaps. Lecture 23 Jérôme Waldispühl School of Computer Science McGill University

COMP250: Priority queue ADT, Heaps. Lecture 23 Jérôme Waldispühl School of Computer Science McGill University COMP250: Priority queue ADT, Heaps Lecture 23 Jérôme Waldispühl School of Computer Science McGill University Priority queue ADT Like a dictionary, a priority queue stores a set of pairs (key, info) The

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements B-Trees 1 B-Trees nodes with many children a type node a class for B-trees 2 manipulating a B-tree an elaborate example the insertion algorithm removing elements MCS 360 Lecture 35 Introduction to Data

More information

Module 2: Priority Queues

Module 2: Priority Queues Module 2: Priority Queues CS 240 Data Structures and Data Management T. Biedl K. Lanctot M. Sepehri S. Wild Based on lecture notes by many previous cs240 instructors David R. Cheriton School of Computer

More information

Priority Queues. Priority Queue. Keys and Total Order Relations. The Priority Queue ADT

Priority Queues. Priority Queue. Keys and Total Order Relations. The Priority Queue ADT Priority Queues Priority Queue The priority queue ADT Implementing a priority queue with a Elementary sorting using a Priority Queue Issues in sorting Queue where we can insert in any order. When we remove

More information

Priority Queue Sorting

Priority Queue Sorting Priority Queue Sorting We can use a priority queue to sort a list of comparable elements 1. Insert the elements one by one with a series of insert operations 2. Remove the elements in sorted order with

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees called the left and right subtrees which are disjoint

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

Priority Queues Heaps Heapsort

Priority Queues Heaps Heapsort Priority Queues Heaps Heapsort Complete the Doublets partner(s) evaluation by tonight. Use your individual log to give them useful feedback! Like 230 and have workstudy funding? We are looking for CSSE230

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Heaps in C. CHAN Hou Pong, Ken CSCI2100 Data Structures Tutorial 7

Heaps in C. CHAN Hou Pong, Ken CSCI2100 Data Structures Tutorial 7 Heaps in C CHAN Hou Pong, Ken CSCI2100 Data Structures Tutorial 7 Review on Heaps A heap is implemented as a binary tree It satisfies two properties: MinHeap: parent = child]

More information

CS2 Algorithms and Data Structures Note 6

CS2 Algorithms and Data Structures Note 6 CS Algorithms and Data Structures Note 6 Priority Queues and Heaps In this lecture, we will discuss priority queues, another important ADT. As stacks and queues, priority queues store arbitrary collections

More information

Priority Queues and Binary Heaps

Priority Queues and Binary Heaps Yufei Tao ITEE University of Queensland In this lecture, we will learn our first tree data structure called the binary heap which serves as an implementation of the priority queue. Priority Queue A priority

More information

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps CS 240 Fall 2015 Mike Lam, Professor Priority Queues and Heaps Priority Queues FIFO abstract data structure w/ priorities Always remove item with highest priority Store key (priority) with value Store

More information

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 201 Heaps 201 Goodrich ad Tamassia xkcd. http://xkcd.com/83/. Tree. Used with permissio uder

More information

Priority queue ADT Heaps. Lecture 21

Priority queue ADT Heaps. Lecture 21 Priority queue ADT Heaps Lecture 21 Priority queue ADT Like a dic9onary, a priority queue stores a set of pairs (key, info) The rank of an object depends on its priority (key) Rear of queue Front of queue

More information

Tutorial AVL TREES. arra[5] = {1,2,3,4,5} arrb[8] = {20,30,80,40,10,60,50,70} FIGURE 1 Equivalent Binary Search and AVL Trees. arra = {1, 2, 3, 4, 5}

Tutorial AVL TREES. arra[5] = {1,2,3,4,5} arrb[8] = {20,30,80,40,10,60,50,70} FIGURE 1 Equivalent Binary Search and AVL Trees. arra = {1, 2, 3, 4, 5} 1 Tutorial AVL TREES Binary search trees are designed for efficient access to data. In some cases, however, a binary search tree is degenerate or "almost degenerate" with most of the n elements descending

More information

Priority Queues Heaps Heapsort

Priority Queues Heaps Heapsort Priority Queues Heaps Heapsort After this lesson, you should be able to apply the binary heap insertion and deletion algorithms by hand implement the binary heap insertion and deletion algorithms explain

More information