1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

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)
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.
Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Priority Queues and Heaps. Overview Our last ADT: PriorityQueueADT A new data structure: heaps One more sorting algorithm: heapsort Priority Queues and.
The Heap ADT In this section of notes you will learn about a new abstract data type, the heap, as well how heaps can be used.
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.
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.
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.
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.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
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:
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Priority Queue What is that? Implementation with linked list with O(n) behaviour The Heap (O(log(n)) An implementation using an array Your mission …
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
P p Chapter 10 has several programming projects, including a project that uses heaps. p p This presentation shows you what a heap is, and demonstrates.
Priority Queues Dr. David Matuszek
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
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.
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.
Queues, Stacks and Heaps. Queue List structure using the FIFO process Nodes are removed form the front and added to the back ABDC FrontBack.
CS 361 – Chapter 5 Priority Queue ADT Heap data structure –Properties –Internal representation –Insertion –Deletion.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
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”
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CS 367 Introduction to Data Structures Lecture 8.
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.
Priority Queues and Heaps Tom Przybylinski. Maps ● We have (key,value) pairs, called entries ● We want to store and find/remove arbitrary entries (random.
CSE373: Data Structures & Algorithms Priority Queues
Chapter 11 Heap.
Priority Queues and Heaps
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,
Heaps © 2010 Goodrich, Tamassia Heaps Heaps
Chapter 8 – Binary Search Tree
Part-D1 Priority Queues
CSE 373: Data Structures and Algorithms
CSE332: Data Abstractions Lecture 4: Priority Queues
Priority Queues.
Tree Representation Heap.
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
Priority Queues & Heaps
1 Lecture 10 CS2013.
CSE 373 Priority queue implementation; Intro to heaps
Priority Queues.
Priority Queues & Heaps
CS210- Lecture 13 June 28, 2005 Agenda Heaps Complete Binary Tree
Presentation transcript:

1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap

2 Purpose: In this lecture we will discuss the Priority Queue ADT and a Heap implementation of a priority Queue

3 Resources: Java Methods AB Data Structures Chapter 7 p.175 Java Essentials Study Guide Chapter 17.7/8 p.330 & Chapter 20.1 p.398 & Chapter 20A.4/5 p.418 Barrons Chapter 9 p.305 & Chapter 12 p.414 AP Java Text Chapter 19.7 p.843 & Chapter 21.4 p.950

4 Handouts: 1.Priority Queue Interface CODE: PriorityQueue.java PriorityString.java PriorityQueueExample.java Jobs.java

5 Intro: So far we have seen data structures that maintain and process data in the following ways: Store data in order based on a Key Store data in order based on the “value” of the object Store data in order of arrival Store data in reverse order of its arrival Store data in random order

6 There are times when we need to maintain and process data based on their relative importance or Priority

7 For example, people waiting to but concert tickets. The priority of the order they are allowed to purchase tickets is based on the number on a wrist band that are distributed. The number on the wristband determines when they get served

8 If you go to an amusement park, you can select a predetermined time to get on an attraction. When the time comes, you get into a Priority Queue which gets processed first

9 In a hospital emergency room, a triage system identifies the urgent patients all of whom are seem before the normal patients regardless of their order of arrival

10 In operating systems, jobs are processed based on a specific priority so that a recently submitted job with a high priority will process before lower priority jobs even though these jobs were in the queue longer

11 What we Will Cover in This Lecture: Priority Queue ADT Priority Queue AP Interface Priority Queue Implementations Heap Implementation The AP AB Requirements

12 Priority Queue ADT PQ’s Support functionality that maintains a large set of elements that are ranked in some way and to have quick access to the HIGHEST ranked element

13 Priority Queue ADT PQ is a collection of the same type object values These object values contain data and a priority These objects are ordered in a way that allows the HIGHEST priority item to be removed first

14 Example of a priority queue where items entered have a priority of 1,2 or 3: EMPTY PQ (ADD) A (2) B (2) A (2) C (2) B (2) A (2) (REMOVE MIN) C (2) B(2) (ADD) D (3) C (2) B(2) (REMOVE MIN) D (3) C (2) (ADD) E (1) D (3) C (2) F (1) E (1) D (3) C (2) (REMOVE MIN) F (1) D (3) C (2) D (3) C (2) D (3) EMPTY PQ

15 If several items maintain the same priority then the first one in the queue is processed first

16 Priority Queues Must Provide for the adding and removing of elements in a way that ensures the HIGHEST Priority Item is removed First Here is the Priority Queue AP Interface :

17 public interface PriorityQueue { boolean isEmpty(); void add(Object x); Object removeMin(); Object peekMin(); }

18 The priority of each item in the queue is established using the Comparable interface Every time the removeMin or peekMin method is executed the SMALLEST element with respect to the compareTo method is returned

19 Priority Queue Implementations You are not required to know one specific PQ implementation but you need to understand their general principles that require any Data Structure to allow for: Quick insertion of PQ elements Quick retrieval of an element with the top priority Potential PQ implementations include:

20 Linked List where new nodes are inserted at the front of the list O(1) and the removal searches the list for the highest priority node O(n)

21 Linked List where nodes are inserted in priority order with the smallest elements in the front nodes O(n) and removal simply unlinks the front node O(1)

22 Array with nodes inserted at the end of the List O(1) and removals search for the highest priority element O(n)

23 A sorted Array where the highest priority elements (smallest values) are added at the end of the List O(n) and removal takes off he last element in the array O(1)

24 TreeSet where adding an element is O(Log N) and Removal is O(Log N)

25 Heap Implementation The most common implementation of a PQ is a Binary Heap With a PQ we use a Minimum Heap With these type of heaps the VALUE of every node is LESS THAN or EQUAL to that of its children

26 A HEAP is viewed as a Complete Binary Tree where there are no GAPS at any level. The Last level may have some leaves missing on the right, but every node except the last must have a node after it. The nodes are in the leftmost positions

27 Each addition to the heap MUST maintain the property where the parent node is at least as small as its children

28 Example:

29 The lower the number, the higher the priority The element with the HIGHEST priority is kept at the root so removing an element requires removal of the root and then restructuring of the heap

30 ReHeaping is a O(LogN) operation Inserting into the heap also requires Reheaping and is O(LogN) ALL elements added to a PQ must implement the Comparable interface and be of the same class

31 Inserting and Removing elements to the Heap

32 create a heap:

33 create a heap:

34 create a heap:

35 Create a heap:

36 Create a heap:

create heap:

38 create heap:

39 create heap:

40 Given the following Tree:

41 Match this heap with an indices of an Array: Heap PriorityArray Element (IGNORE ZERO)

42 Array Index:

43 Lets Insert an element with a priority of 5 We insert the new element in the next open slot ( index 10 or left child of element with Priority of 7)

44 We then Compare This element against its Parent

45 If the Parent is Greater, Then SWAP the elements

46 We AGAIN Compare This element against its Parent

47 If the Parent is Greater, Then SWAP the elements

48 Lets Insert an element with a priority of 5 We insert the new element in the next open slot ( index 10 or left child of element with Priority of 7)

49 Lets Insert an element with a priority of 5 We insert the new element in the next open slot ( index 10 or left child of element with Priority of 7)

50 Again We Compare This Element against its New Parent But since the Parent is SMALLER than the this element, we are done RE-HEAPING The order of the Heap is maintained as all children are LARGER than their parent

51 The Heap has been updated and its order of priority maintained

52 We can implement a Heap as a Binary Tree but it is more efficient to implement a Binary Heap as an Array Using your own array or the ArrayList

53 Non-Linked Representation of Binary Trees is a more efficient way of implementing heaps. Here all nodes are stored in an array in a certain order so that for each node it is easy to find its children and its parent

54 EXAMPLE: Given the previous PQ, the following is the construction of the array at each stage of insertion:

56 If you match the element number, starting at element 1, with the Binary Heap, you will see an exact correlation

57 Treeelement #s 2 1 / \ / \ / \ / \ / \ / \

58 Each level contains twice as many nodes as the preceding level.

59 The left and right children of the i-th node, if they are present, have the numbers 2i and 2i+1 and its parent has the number i/2 (truncated to an integer)

60 Using this algorithm, we can manipulate an array as a Binary HEAP

61 REMEMBER THAT A COMPLETE TREE is a tree where there are no GAPS at any level. The Last level may have some leaves missing on the right, but every node except the last must have a node after it. The nodes are in the leftmost positions

62 REMEMBER THAT A COMPLETE TREE is a tree where there are no GAPS at any level. The Last level may have some leaves missing on the right, but every node except the last must have a node after it. The nodes are in the leftmost positions

63 A Complete Tree

64 Binary Trees: a non-linked representation:

65 This property allows us to store a complete tree in an array where the element x[n] corresponds to node number n Count the elements of the array starting from element 1 (leave element 0 unused)

66 Heap remove deletes an element from the root of the heap Then the heap needs to be adjusted to preserve its ordering property and to keep it a complete tree. Remove the root (first element in the heap)

67 Place the last element of the heap into its root (first element). This is the RIGHTMOST node in the lowest tree level Then move down from level to level, swapping it with its smaller child until it falls into place

68 This process is called the REHEAP DOWN procedure

69 Using our previous example, execute a remove

70 We take the last element in the heap (10th index / value #7) and move it to the top of the heap Then swap this element with its smaller child Swap #7 with #4 Continue this until this node is smaller than its children

71 The heap now looks like this:

72 We can also have a Maximum Heap where all elements are Stored with the HIGHEST value at the top of the heap Here, all parents have a HIGHER value than their children

73 Here element x[1] of the array corresponds to the root of the heap. Example: queued items

74 TREEVIEW:

75 ARRAYVIEW:Element #Value 0unused

76 Priority Queues maintain data as well as a priority You can create a class that serves as the “element” that is stored in the Heap

77 In the PriorityString class there is a data part and an Integer that represents the objects priority The SMALLER the number the HIGHER the priority

78 Lets look at the PriorityString.java class in the handout

79 We have the PriorityQueue Interface, but we need an implementation of that interface so we can maintain our Heap The ArrayPriorityQueue.java class implements the Priority Queue as an ArrayList

80 Lets look at the ArrayPriorityQueue.java class in the handout

81 Finally, to put it all together we use our Array Priority Queue in a Driver Program Lets look at PriorityQueueExample.java in our handout

82 RUN the Priority QueuesAndExamples.java RUN and Review the program JOBS.JAVA

83 AP AB Subset Requirements Students are expected to: Understand the PQ ADT How the PriorityQueue Interface methods can be implemented (insert, remove, peek, reheap) Create a Class that is used as the element of a PQ Utilize a PQ implementation in a Driver program

84 LABS:Write a Heap Class Multiple Choice from Barrons: Chapter 9 p.317 #s 14 to 18