COMP 103 Priority Queues, Partially Ordered Trees and Heaps.

Slides:



Advertisements
Similar presentations
PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring
Advertisements

COMP 103 Linked Stack and Linked Queue.
Priority Queues. 2 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.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
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.
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.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Dr. Andrew Wallace PhD BEng(hons) EurIng
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
Priority Queues and Heaps Bryce Boe 2013/11/20 CS24, Fall 2013.
1 Chapter 25 Trees Iterators Heaps Priority Queues.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Trees, Binary Search Trees, Recursion, Project 2 Bryce Boe 2013/08/01 CS24, Summer 2013 C.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Information and Computer Sciences University of Hawaii, Manoa
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Data Structures Week 8 Further Data Structures The story so far  Saw some fundamental operations as well as advanced operations on arrays, stacks, and.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Outline Priority Queues Binary Heaps Randomized Mergeable Heaps.
Topic 24 Heaps "You think you know when you can learn, are more sure when you can write even more when you can teach, but certain when you can program."
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Heaps & Priority Queues
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
2015-T2 Lecture 30 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
2014-T2 Lecture 29 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae and Thomas.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
CS 367 Introduction to Data Structures Lecture 8.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
2015-T2 Lecture 28 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae and Thomas.
COMP 103 Course Review. 2 Menu  A final word on hash collisions in Open Addressing / Probing  Course Summary  What we have covered  What you should.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
CS 201 Data Structures and Algorithms
Heaps (8.3) CSE 2011 Winter May 2018.
BST Trees
Source: Muangsin / Weiss
COMP 103 Sorting with Binary Trees: Tree sort, Heap sort Alex Potanin
COMP 103 HeapSort Thomas Kuehne 2013-T1 Lecture 27
More complexity analysis & Binary Search
COMP 103 Binary Search Trees.
CMSC 341 Lecture 13 Leftist Heaps
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
- Alan Perlis Heaps "You think you know when you can learn,
- Alan Perlis Topic 24 Heaps "You think you know when you can learn,
ITEC 2620M Introduction to Data Structures
CE 221 Data Structures and Algorithms
Priority Queues & Heaps
CSC 143 Binary Search Trees.
Priority Queues.
Interesting Algorithms for Real World Problems
Presentation transcript:

COMP 103 Priority Queues, Partially Ordered Trees and Heaps

2 RECAP-TODAY RECAP Clever stuff with linked structures linked list idea  nice way to implement a Stack, or a Queue  Then we saw trees, and then Binary Search Trees (BST) adding, and finding (significance of balance) removing is “interesting” BST idea  nice way to implement a Set, Bag, or Map in-order traversals  TreeSort TODAY:  Priority queue (PQ) – variation on queue – “best” first  partially ordered tree (POT)  nice way to implement PQ  oh and we’ll also get another fast sorting algorithm!  Reading: Chapter 17 (section )

3 Queues and priority queues  Queues: First in, first out ⇒ Oldest out first  Priority Queues: Highest priority (“best”) out first  Emergency room, 111 calls, job scheduling in factory, etc...  Operating system process scheduling  Graph/network algorithms: route planning, find shortest/cheapest path  AI search algorithms BobJackJimIan BobJackJimIan 1432 Sometimes low number means high priority!

4 Implementing Priority Queues  Unsorted list (array or linked list):  Fast to enqueue (“offer”): O(1)  Slow to dequeue (“poll”): O(n) have to search for highest priority item.  Sorted list (array or linked list):  Fast to dequeue (“poll”): O(1) ‏  Slow to enqueue (“offer”): O(n) have to search for insertion point (and move items up).  Array of “Buckets” of queues for each priority:  Fast to enqueue and dequeue: O(1) ‏  Requires a small finite number of priorities.  Best choice when applicable

5 Implementing Priority Queues: preview...  So, what to do when we have unlimited priorities?  Binary Search Tree:  Keeps items in order, and allows easy insertion  Fast to enqueue: O(log n) [if balanced]  Fast to dequeue: O(log n) [if balanced] How?  But, hard to keep balanced  Partially Ordered Tree:  Fast to enqueue (“offer”): O(log n)  Fast to dequeue (“poll”): O(log n) ‏  Keeps itself balanced!  Fast to construct from unordered list!

6 Partially Ordered Trees Binary Search Tree:  Binary tree  All left subtree < parent, All right subtree ≥ parent. Partially Ordered Tree Binary tree Children ≤ parent, Order of children not important Cat 19 Eel 26 Gnu 13 Fox 3 Dog 14 Bee 35 Hen 23 Ant 9 Bee 35 Eel 26 Cat 19 Dog 14 Fox 3 Ant 9 Hen 23 Gnu 13 Jay 1 Jay 1 Keep largest (or smallest) element at the root.

7 Partially Ordered Tree: add  Easier to add and remove because the order is not complete.  Add:  insert at bottom rightmost  “push up” to correct position. (swapping) Bee 35 Eel 26 Cat 19 Dog 14 Fox 3 Ant 9 Hen 23 Gnu 13 Jay 1 Kea 24

8 Partially Ordered Tree: remove  Easier to add and remove because the order is not complete.  Add:  insert at bottom rightmost  “push up” to correct position.  Remove:  “pull up” largest child and recurse.  But: makes tree unbalanced! Bee 35 Eel 26 Kea 24 Dog 14 Cat 19 Ant 9 Hen 23 Gnu 13 Jay 1 Fox 3

9 Partially Ordered Tree: remove I  Easier to add and remove because the order is not complete.  Add:  insert at bottom rightmost  “push up” to correct position.  Remove:  “pull up” largest child of root and recurse on that subtree.  But: makes tree unbalanced! Alternative:  replace root by bottom rightmost node  “push down” to correct position (swapping)  keeps tree balanced – and complete! Bee 35 Eel 26 Kea 24 Dog 14 Cat 19 Ant 9 Hen 25 Gnu 13 Jay 1 Fox 3

10 Partially Ordered Tree: remove II  Easier to add and remove because the order is not complete.  Add:  insert at bottom right  “push up” to correct position.  Remove:  “pull up” largest child and recurse.  But: makes tree unbalanced! Alternative:  replace root by bottom rightmost node  “push down” to correct position  keeps tree balanced – and complete! Eel 26 Hen 23 Kea 24 Dog 14 Cat 19 Ant 9 Fox 3 Gnu 13 Jay 1

11 Partially Ordered Tree  Add: insert at bottom rightmost, swap with parent, …  Remove: replace root with bottom rightmost, swap with largest child, … But:  How do you find the bottom right?  Once you have found it, how do you find its parent to push it up? We need a tree where you can quickly get to:  the bottom right node,  children from parent,  parent from children. Bee 35 Eel 26 Cat 19 Dog 14 Fox 3 Ant 9 Hen 23 Gnu 13 Jay 1 Kea 24

12 Heap:  A complete, partially ordered, binary tree complete = every level full, except bottom, where nodes are to the left  Implemented in an array using breadth-first order Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Cat 4 Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Cat

13 Heap  We can compute the index of parent and children of a node:  the children of node i are at (2i+1) and (2i+2)  the parent of node i is at (i-1)/2  Bottom right node is last element used.  There are no gaps! Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Cat Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Cat 4

14 Heap: add Insert at bottom of tree and push up:  Put new item at end: 10  Compare with parent: (10-1)/2 = 4 ⇒ Fox/7  If larger than parent, swap  Compare with parent: (4-1)/2 = 1 ⇒ Kea/19  If larger than parent, swap  Compare with parent: (1-1)/2 = 0 ⇒ Bee/35 Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Cat Pig 21 11

15 Heap: remove  Remove item at 0:  Move last item to 0  Find largest child 2  0+1 = 1, 2  0+2 = 2  If smaller than largest child, swap  Find largest child 2  2+1 = 5, 2  2+2 = 6  If smaller than largest child, swap  Find largest child 2  5+1 = 11 : No such child Bee 35 Eel 26 Pig 21 Dog 14 Kea 19 Ant 9 Hen 23 Gnu 13 Jay 1 Cat Fox 7 11

16 HeapQueue public class HeapQueue extends AbstractQueue { private List data = new ArrayList (); private Comparator comp; public HeapQueue (Comparator c) { comp = c; } public boolean isEmpty() { return data.isEmpty(); } public int size () { return data.size(); } public E peek () { if (isEmpty()) return null; else return data.get(0); } Use ArrayList, not array, so it handles resizing. Comparator must be designed so that it compares the priority values (not the items) Note to whoever teaches this next: I think it’d be better to present this in terms of ordinary array notation, because it’s easier to see what it’s doing, and leave it to them as an exercise to reimplement it using ArrayList once they understand it. I think the coding used for pushup and pushdown (ie writing things like data.set(child, data.set(parent, data.get(child)));) is revolting and should not be inflicted up poor struggling first year students! I’ve changed it to use a method which at least makes the intention clear. Also, this code doesn’t distinguish between the values in the priority queue and their priorities. It can be made to work IF the comparator you use can extract a priority from an object, but if that is what is intended, it needs to be explained. I worked all this out too late to fix it this time round, so and adding this note to help whoever does it next time. Lindsay

17 HeapQueue: offer and poll public boolean offer(E value) { if (value == null)return false; else { data.add(value); pushup(data.size()-1); return true; } public E poll() { if (isEmpty())return null; if (data.size() == 1)return data.remove(0); else { E ans = data.get(0); data.set(0, data.remove(data.size()-1)); pushdown(0); return ans; } add at the end of the array move last element into root

18 HeapQueue: pushup private void pushup(int child) { if (child == 0) return; int parent = (child-1)/2; // compare with value at parent and swap if parent smaller if (comp.compare(data.get(parent), data.get(child)) < 0) { swap(data, child, parent); pushup(parent); } private void swap(List data, int from, int to) data.set(child, data.set(parent, data.get(child))); Bee 35 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay 1 Tui recurse up the tree...

19 HeapQueue: pushdown private void pushdown(int parent) { int largeCh = 2*parent+1; int otherCh = largeCh+1; // check if any children if (largeCh >= data.size()) return; // find largest child if (otherCh < data.size() && comp.compare(data.get(largeCh), data.get(otherCh)) < 0 ) largeCh = otherCh; // compare with largest child, and swap if smaller if (comp.compare(data.get(parent), data.get(largeCh)) < 0) { swap(data, largeCh, parent); pushdown(largeCh); } Cat 4 Eel 26 Kea 19 Dog 14 Fox 7 Ant 9 Hen 23 Gnu 13 Jay recurse down the tree...

20 HeapQueue: Analysis  Cost of offer: = cost of pushup = O(log(n)) log(n) comparisons, 2 log(n) assignments  Cost of poll: = cost of pushdown = O(log(n)) 2 log(n) comparisons, 2 log(n) assignments  Conclusion: HeapQueue is always fast!!