1 Heaps and Priority Queues Heap Definition and Operations Using Heaps –Heap sort –Priority queues Implementing heaps –With links –With arrays –Analysis.

Slides:



Advertisements
Similar presentations
Priority Queues1 Priority Queues (Antrian Berprioritas)
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 9.
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Treaps.  Good (logarithmic) performance with random data  Linear performance if the data is sorted ◦ Solutions – Splay Trees Amortized O( lg n) performance.
Priority Queues CSC 172 SPRING 2002 LECTURE 16. Priority Queues Model Set with priorities associate with elements Priorites are comparable by a < operator.
Chapter 15 Heaps. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a heap abstract data structure Demonstrate.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
DictionaryADT and Trees. Overview What is the DictionaryADT? What are trees? Implementing DictionaryADT with binary trees Balanced trees DictionaryADT.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
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,
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
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.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
Information and Computer Sciences University of Hawaii, Manoa
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 10: Binary Search Trees Java Software Structures: Designing.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
data ordered along paths from root to leaf
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
Chapter 20 Binary Search Trees
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
Heaps and Heap Sorting Heaps implemented in an Array Heap Sorting.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
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.
Heaps A heap is a binary tree that satisfies the following properties: Structure property: It is a complete binary tree Heap-order property: Each node.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
Priority Queues CS /02/05 L7: PQs Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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.
1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
The Tree ADT.
Heaps 8/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Trees and Binary Search Trees
Trees Tree nomenclature Implementation strategies Traversals
Part-D1 Priority Queues
Chapter 21 Heaps and Priority Queues
Heaps 9/13/2018 3:17 PM Heaps Heaps.
Priority Queues Linked-list Insert Æ Æ head head
ADT Heap data structure
Priority Queues.
CSE 373: Data Structures and Algorithms
Heaps and Heap Sorting Heaps implemented in an Array Heap Sorting.
Priority Queues.
Hassan Khosravi / Geoffrey Tien
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
CHAPTER 11: Priority Queues and Heaps
1 Lecture 10 CS2013.
Heaps 9/29/2019 5:43 PM Heaps Heaps.
Chapter 20 Binary Search Trees
Chapter 21 Heaps and Priority Queues
Presentation transcript:

1 Heaps and Priority Queues Heap Definition and Operations Using Heaps –Heap sort –Priority queues Implementing heaps –With links –With arrays –Analysis of heap implementations Reading: L&C 12.1 – 12.5

2 Heap Definition A heap is a binary tree with added properties –It is a complete tree (as defined earlier) –For each node, the parent is less than or equal to both its left and its right child (a min heap) OR –For each node, the parent is greater than or equal to both its left and its right child (a max heap) For simplicity, we will study only a min heap Class of objects stored in a heap may implement Comparable interface or a Comparator may be used

3 Heap Operations > BinaryTreeADT + removeLeftSubtree( ) : void + removeRightSubtree( ) : void + removeAllElements( ) : void + isEmpty( ) : boolean + size( ) : int + contains( ) : boolean + find( ) : T + toString( ) : String + iteratorInOrder( ) : Iterator + iteratorPreOrder( ) : Iterator + iteratorPostOrder( ) : Iterator + iteratorLevelOrder( ) : Iterator Note: toString is missing in L&C Fig 11.2 > HeapADT + addElement(element : T) : void + removeMin() : T + findMin( ) : T

4 Heap Operations Notice that we are extending BinaryTreeADT – not BinarySearchTreeADT We don’t use BinarySearchTree operations We define different heap operations to add and remove elements according to the new definition of the storage order for a heap –addElementO(log n) –RemoveMinO(log n) –findMinO(1)

5 Heap Operations Semantics for addElement operation –Location of new node Next insertion point

6 Heap Operations Semantics for addElement operation –Add 2 in the next available position –Reorder (“heapify on add”) Compare new node with parent and swap if needed Continue up the tree until at root if necessary

7 Heap Operations Semantics of removeMin operation –Remove root node –Replace root with last leaf –Reorder the heap (“heapify on remove”) Remove Replace root with Reorder

Heap Operations Heapify on Remove –Start at root –Find smallest child –If root greater than smallest child (min heap), swap parent with smallest child –Continue at child node until no swap needed 8

9 Heap Operations Semantics of findMin operation –The min element is always at the root element –Just return a reference to the root’s element Return a reference to root

10 Using Heaps Heap Sort –Add each element to a heap –Remove them one at a time Sort Order –Min heap  ascending order –Max heap  descending order Performance –O(n log n)

11 Using Heaps Priority Queue Applications –Task scheduling in an operating system –Traffic scheduling on a network link –Job scheduling at a service center –Creating a Huffman coding tree Write the compareTo method to compare priorities which heap logic uses first If there is a tie on priority, heap logic uses order of entry (FIFO within priority)

12 Implementing Heaps with Links HeapNode BinaryTreeNode Heap LinkedBinaryTree # parent : HeapNode > HeapADT # lastNode : HeapNode

13 Implementing Heaps with Links Class HeapNode public class HeapNode extends BinaryTreeNode { protected HeapNode parent; public HeapNode (T obj); { super(obj); parent = null; } Class Heap public class Heap extends LinkedBinaryTree implements HeapADT { private HeapNode lastNode;

14 Implementing Heaps with Links Heap addElement operation public void addElement (T obj) { HeapNode node = new HeapNode (obj); if (root == null) root=node; else { HeapNode next_parent = getNextParentAdd(); if (next_parent.getLeft() == null; next_parent.setLeft(node); else next_parent.setRight(node); node.setParent(next_parent); }

15 Implementing Heaps with Links Heap addElement operation lastNode = node; count++; if (count > 1) heapifyAdd(); } private void heapifyAdd() // a helper method { HeapNode next = lastNode; while ((next != root) && (((Comparable)next.getElement()).compareTo (next.getParent().getElement()) < 0)) { T temp = next.getElement(); next.setElement(next.getParent().getElement()); next.getParent().setElement(temp); next = next.getParent(); }

16 Implementing Heaps with Links Heap addElement operation private HeapNode getNextParentAdd() //a helper { HeapNode result = lastNode; // go up right branch as needed while (result != root && result.getParent().getLeft() != result) result = result.getParent(); // at top of a left branch or at root now if (result == root) // at root, go down left branch to lower left while (result.getLeft() != null) result = result.getLeft(); else

17 Implementing Heaps with Links Heap addElement operation { // need to go over the hump to a right branch if (result.getParent().getRight() == null) // parent is the next parent result = result.getparent(); else { // parent is an ancestor of the next parent result = (HeapNode )result.getParent(). getRight(); // go down its left branch to bottom level while result.getLeft() != null) result = (HeapNode ) result.getLeft(); } return result; }

18 Implementing Heaps with Links Heap removeMin operation public T removeMin() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(“Empty heap”); T minElement = root.getElement(); if (count ==1) { root = null; lastNode = null; } else

19 Implementing Heaps with Links Heap removeMin operation { HeapNode next_last = getNewlastNode(); if (lastNode.getParent().getLeft() == lastNode) lastNode.getparent().setLeft(null); else lastNode.getParent().setRight(null); root.setElement(lastNode.getElement()); lastNode = next_last; heapifyRemove(); } count--; return minElement; }

20 Implementing Heaps with Links Heap removeMin operation private HeapNode getNewLastNode() // a helper { HeapNode result = lastNode; while (result != root && result.getParent().getLeft() == result) result = result.getParent(); if (result != root) result = (HeapNode ) result.getParent().getLeft(); while (result.getRight() != null) result = (HeapNode ) result.getRight(); return result; }

21 Implementing Heaps with Links Heap removeMin operation private void heapifyRemove() // a helper method { if (root == null) return; HeapNode node = null; HeapNode next = (HeapNode )root; do { if (node != null) { // skip on first pass T temp = node.getElement(); node.SetElement(next.getElement()); next.setElement(temp); } node = next;

22 Implementing Heaps with Links Heap removeMin operation HeapNode left = (HeapNode )node.getLeft(); HeapNode right = (HeapNode )node.getRight(); if ((left == null) && (right == null)) next = null; else if (left == null) next = right; else if (right == null) next = left; else if (((Comparable)left.getElement()). compareTo(right.getElement()) < 0) next = left; else next = right; } while (next != null && ((Comparable)next.getElement()). compareTo(node.getElement()) < 0); }