Implementing a Priority Queue

Slides:



Advertisements
Similar presentations
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)
Advertisements

1 HeapSort CS 3358 Data Structures. 2 Heapsort: Basic Idea Problem: Arrange an array of items into sorted order. 1) Transform the array of items into.
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.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
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.
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.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
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.
David Luebke 1 12/23/2015 Heaps & Priority Queues.
Heaps & Priority Queues
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”
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
1 Heap Sort. A Heap is a Binary Tree Height of tree = longest path from root to leaf =  (lgn) A heap is a binary tree satisfying the heap condition:
1 Queues Queue API Application: Radix Sort Implementation: Using Deque Using Deque Circular Array Circular Array Priority Queue Priority Queue API Implementation.
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.
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.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Heaps and Priority Queues What is a heap? A heap is a binary tree storing keys at its internal nodes and satisfying the following properties:
Heaps and Heap Sort. Sorting III / Slide 2 Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves)
Sorting With Priority Queue In-place Extra O(N) space
Priority Queues A priority queue is an ADT where:
"Teachers open the door, but you must enter by yourself. "
Heaps, Heap Sort and Priority Queues
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
Heap Sort Example Qamar Abbas.
Priority Queues (Heaps)
Priority Queues Sections 6.1 to 6.5.
Priority Queues Linked-list Insert Æ Æ head head
The Heap Data Structure
7/23/2009 Many thanks to David Sun for some of the included slides!
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Chapter 8 – Binary Search Tree
Priority Queue & Heap CSCI 3110 Nan Chen.
Heapsort Heap & Priority Queue.
What is a heap? Always keep the thing we are most interested in close to the top (and fast to access). Like a binary search tree, but less structured.
Heaps, Heapsort, and Priority Queues
Draw pictures to indicate the subproblems middleMax solves at each level and the resulting maxPtr and PrevPtr for each on this linked list:
Lecture 13 – Heaps Container Adapters priority_queue – impl. with heap
CSE 373: Data Structures and Algorithms
CMSC 341 Lecture 14 Priority Queues & Heaps
Heapsort.
ITEC 2620M Introduction to Data Structures
Tree Representation Heap.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Hassan Khosravi / Geoffrey Tien
Computer Science 2 Heaps.
Heap Sort The Heap Data Structure
"Teachers open the door, but you must enter by yourself. "
Heaps A heap is a binary tree that satisfies the following properties:
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) A heap.
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
Priority Queues & Heaps
Sorting Dr. Yingwu Zhu.
Algorithms: Design and Analysis
CSE 373, Copyright S. Tanimoto, 2002 Priority Queues -
Heaps By JJ Shepherd.
Hash Maps: The point of a hash map is to FIND DATA QUICKLY.
Computer Algorithms CISC4080 CIS, Fordham Univ.
Heaps & Multi-way Search Trees
EE 312 Software Design and Implementation I
Presentation transcript:

Implementing a Priority Queue Heaps

Priority Queues Recall: 3 Container Adapters Priority Queue Stack Priority Queue – implementation? Priority Queue Uses std::vector Maintains complete tree w/special ordering property Vector w/property is Heap

Binary Trees V <= V > V

Heaps (Max Heap) V <= V <= V

Binary Tree vs. Heap 6 13 3 9 9 3 1 7 13 7 6 1

Heap Shape Property A heap must be a “complete” binary tree This means the levels of the tree will always be filled from left-to-right 13 Level 0 9 3 Level 1 7 6 1 Level 2

Insertion 13 9 3 7 6 1

Insertion 13 9 3 To maintain the Shape property, we must insert at the end of level 2 7 6 1 8

Insertion 13 9 3 But if we insert the 8 there the heap ordering property isn’t maintained! 8 <= 3  7 6 1 8

Insertion 13 8 <= 13  9 8 So we do the only sensible thing and swap the values! 3 <= 8  7 6 1 3

Insertion 9 8 This strategy applies for more than one “step”, too 7 6 13 9 8 This strategy applies for more than one “step”, too 7 6 1 3 18

Insertion 13 9 8 18 <= 7  7 6 1 3 18

Insertion 13 9 8 18 <= 9  18 6 1 3 7

Insertion 13 18 8 18 <= 13  9 6 1 3 7

Insertion 18 13 8 13 <= 18  9 6 1 3 7

Insertion – Done 18 13 8 The “13” node “bubbled up” from the bottom to its final position This operation is known as upheap() while n.data > parent(n).data: swap(n.data, parent(n).data) n = parent(n) if n == null: break 9 6 1 3 7

Removal We can only remove from the top 18 We can only remove from the top We need to maintain the shape property We need to maintain ordering property 13 8 9 6 1 3 7

Removal 7 Swap the “root” with the last We compare the node with its two children Choose the larger one and swap Repeat until in place 13 8 9 6 1 3 18 removed

Removal Swap the “root” with the last 13 Swap the “root” with the last We compare the node with its two children Choose the larger one and swap Repeat until in place 7 8 9 6 1 3 18 removed

Removal Swap the “root” with the last 13 Swap the “root” with the last We compare the node with its two children Choose the larger one and swap Repeat until in place 9 8 7 6 1 3 18 removed

Removal The “7” node “bubbled down” from the topto its final position 13 The “7” node “bubbled down” from the topto its final position This operation is known as downheap() 9 8 7 6 1 3 18 removed

Heaps Are Arrays parent(i) = (i – 1) / 2 left(i) = 2 * i + 1 13 parent(i) = (i – 1) / 2 left(i) = 2 * i + 1 right(i) = 2 * i + 2 9 8 1 2 7 6 1 3 3 4 5 6

Complete Binary Tree Why store tree in vector? parent (i) = p (i) = ? leftChild (i) = lc (i) = ? rightChild (i) = rc (i) = ?

Max and Min Heaps Max Heap property: ( nodes X) [ Value (X) >= Value (Child (X)) ]

priority_queue::push v.push_back (50);

Upheap (restore heap property) upHeap (v.size () – 1);

Push void PQ::push (const T& item) { v.push_back (item); upHeap (v.size () – 1); }

upHeap (Helper Method) void PQ::upHeap (size_t pos) { T item = v[pos]; size_t i; // Move parent down for (i = pos; i != 0 && item > v[p (i)]; i = p (i)) v[i] = v[p (i)]; // swap unnecessary v[i] = item; }

priority_queue::pop v.front () = v.back (); v.pop_back (); 18

downHeap

Pop void PQ::pop () { v[0] = v.back (); v.pop_back (); // O (1) // Move elem down to proper place downHeap (0); }

downHeap (Helper Method) void PQ::downHeap (size_t pos) { // Move v[pos] down, max child up size_t i, mc; T val = v[pos]; for (i = pos; (mc = lc (i)) < v.size (); i = mc) { if (mc + 1 < v.size () && v[mc] < v[mc + 1]) ++mc; if (val ??) // Move child up if necessary else ? } // Place val in correct spot

Heap Sort Overview Heaps  O(N*lg (N)) sort in worst case Can use heaps to sort in two ways 1) pqSort Push all elements Pop and place in vector back to front Complexity? 2*Sum (i =1:N) [ lg(i) ]

Heap Sort Overview 2) True heap sort (better, why?) “Heapify” vector (O(N)) With STL assistance (make_heap) Roll our own “buildHeap” elemsToPlace = v.size () - 1 while (elemsToPlace > 0) Swap front and back of v --elemsToPlace Restore heap property at root (taking into consideration heap is one elem. smaller) In-place

make_heap (STL) int arr[] { 50, 20, 75, 35, 25 }; // Header <algorithm> make_heap (arr, arr + 5);

buildHeap Potential algorithms (several don’t work!) Call downHeap (0) N times Call downHeap (i) varying i from 0 to N-1 Call downHeap (i) varying i from N-1 to 0 Call upHeap (i) varying i from 0 to N-1 Call upHeap (i) varying i from N-1 to 0

buildHeap Start at last internal node: position = ? Then do downHeap (position)

buildHeap Cont’d

Heap  Sorted Vector Now convert heap to sorted vector Swap front and back Decrease size of heap by 1 downheap (0)

Heap  Sorted Vector 4 2 7 6 9 10 5 3 1 a[ ]: Heap 7 2 4 5 3 9 6 10 a[ ]: Heap 7 2 4 5 3 9 6 10 Heap is in a[0..7] and the sorted region is empty Swap front and back

Heap  Sorted Vector 4 2 7 6 9 3 5 1 10 a[ ]: Semiheap Sorted 10 a[ ]: Semiheap Sorted downHeap a[0..6] now represents a semiheap a[7] is the sorted region 7 2 4 5 9 6 3

Heap  Sorted Vector 4 2 7 6 3 9 5 1 10 a[ ]: Becoming a Heap Sorted 7 10 a[ ]: Becoming a Heap Sorted downHeap 7 2 4 5 3 6 9

Heap  Sorted Vector 4 2 3 6 7 9 5 1 10 a[ ]: Heap Sorted 3 2 4 5 7 6 10 a[ ]: Heap Sorted 3 2 4 5 7 6 9

Heap  Sorted Vector 4 2 3 6 7 5 1 10 9 a[ ]: Semiheap Sorted 3 2 4 7 10 9 a[ ]: Semiheap Sorted downHeap 3 2 4 7 6 5

Heap  Sorted Vector 4 2 3 6 5 7 1 10 9 a[ ]: Heap Sorted 3 2 4 5 6 7 10 9 a[ ]: Heap Sorted downHeap 3 2 4 5 6 7

Heap  Sorted Vector 7 2 3 6 5 4 1 10 9 a[ ]: Semiheap Sorted 3 2 5 6 10 9 a[ ]: Semiheap Sorted downHeap 3 2 5 6 4

Heap  Sorted Vector 7 2 3 4 5 6 1 10 9 a[ ]: Heap Sorted 3 2 5 4 6

Heap  Sorted Vector 7 6 3 4 5 2 1 10 9 a[ ]: Semiheap Sorted 3 5 4 2 10 9 a[ ]: Semiheap Sorted downHeap 3 5 4 2

Transform a Heap Into a Sorted Array: Example 7 6 3 4 2 5 1 10 9 a[ ]: Sorted Becoming a Heap downHeap 3 2 4 5

Heap  Sorted Vector 7 6 2 4 3 5 1 10 9 a[ ]: Heap Sorted 2 3 4 5

Heap  Sorted Vector 7 6 5 4 3 2 1 10 9 a[ ]: Semiheap Sorted 3 4 2 10 9 a[ ]: Semiheap Sorted downHeap 3 4 2

Heap  Sorted Vector 7 6 5 2 3 4 1 10 9 a[ ]: Heap Sorted 3 2 4

Heap  Sorted Vector 7 6 5 4 3 2 1 10 9 a[ ]: Semiheap Sorted 3 2 10 9 a[ ]: Semiheap Sorted downHeap 3 2

Heap  Sorted Vector 7 6 5 4 2 3 1 10 9 a[ ]: Heap Sorted 2 3

Heap  Sorted Vector 7 6 5 4 3 2 1 10 9 a[ ]: Heap Sorted 2

Heap  Sorted Vector 7 6 5 4 3 2 1 10 9 a[ ]: Sorted

Heap Sort (Code) // Create heap from vector bottom up // Start with last internal node // O(N) for “for” loop for (i = (N – 2) / 2; i >= 0; --i) downHeap (i); // O(N lg(N)) for “while” while (N > 1) { swap (v[0], v[N-1]); --N; downHeap (0); }