Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

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.
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
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.
Heaps, Heap Sort, and Priority Queues
Priority Queue (Heap) & Heapsort COMP171 Fall 2006 Lecture 11 & 12.
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.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
More sorting algorithms: Heap sort & Radix sort. Heap Data Structure and Heap Sort (Chapter 7.6)
Heaps and heapsort COMP171 Fall Sorting III / Slide 2 Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Chapter 6: Priority Queues Priority Queues Binary Heaps Mark Allen Weiss: Data Structures and Algorithm Analysis in Java Lydia Sinapova, Simpson College.
Priority Queues  Queues: first-in first-out in printer schedule  Disadvantage: short job, important job need to wait  Priority queue is a data structure.
1 TCSS 342, Winter 2005 Lecture Notes Priority Queues and Heaps Weiss Ch. 21, pp
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
3-Sorting-Intro-Heapsort1 Sorting Dan Barrish-Flood.
Lecture 7 Heaps and Priority Queues. Motivating Example 3 jobs have been submitted to a printer, the jobs have sizes 100, 10, 1 page. Average waiting.
Lecture 7 Heaps and Priority Queues. Motivating Example 3 jobs have been submitted to a printer, the jobs have sizes 100, 10, 1 page. Average waiting.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
Heaps and heapsort COMP171 Fall 2005 Part 2. Sorting III / Slide 2 Heap: array implementation Is it a good idea to store arbitrary.
Heapsort CIS 606 Spring Overview Heapsort – O(n lg n) worst case—like merge sort. – Sorts in place—like insertion sort. – Combines the best of both.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
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.
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.
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 21 Binary Heap.
WEEK 3 Leftist Heaps CE222 Dr. Senem Kumova Metin CE222_Dr. Senem Kumova Metin.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Dan Grossman Fall 2013.
1 Heaps (Priority Queues) You are given a set of items A[1..N] We want to find only the smallest or largest (highest priority) item quickly. Examples:
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.
Priority Queues (Heaps)
Binary Heaps Text Read Weiss, § Binary Heap One-array representation of a tree Complete trees Building a Binary Heap Insert Delete.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
Queues, Stacks and Heaps. Queue List structure using the FIFO process Nodes are removed form the front and added to the back ABDC FrontBack.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
CS223 Advanced Data Structures and Algorithms 1 Priority Queue and Binary Heap Neil Tang 02/09/2010.
Heaps & Priority Queues
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
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.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
CSE332: Data Abstractions Lecture 4: Priority Queues Dan Grossman Spring 2012.
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 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)
"Teachers open the door, but you must enter by yourself. "
CSE373: Data Structures & Algorithms Priority Queues
CS 201 Data Structures and Algorithms
Heaps (8.3) CSE 2011 Winter May 2018.
Priority Queues and Heaps
Source: Muangsin / Weiss
Heaps, Heap Sort, and Priority Queues
Priority Queues (Heaps)
Heaps, Heap Sort, and Priority Queues
CMSC 341: Data Structures Priority Queues – Binary Heaps
Priority Queue & Heap CSCI 3110 Nan Chen.
Heaps and the Heapsort Heaps and priority queues
"Teachers open the door, but you must enter by yourself. "
CE 221 Data Structures and Algorithms
CSC 380: Design and Analysis of Algorithms
Priority Queues (Heaps)
CSE 373, Copyright S. Tanimoto, 2002 Priority Queues -
Data Structures and Algorithm Analysis Priority Queues (Heaps)
Heaps & Multi-way Search Trees
Priority Queues Binary Heaps
Presentation transcript:

Heaps, Heap Sort, and Priority Queues

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 a node x, we denote the left child, right child and the parent of x as left(x), right(x) and parent(x), respectively. root leaf left(x)right(x) x Parent(x)

Height (Depth) of a Binary Tree * The number of edges on the longest path from the root to a leaf. Height = 4

Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves) or 2 children and n All leaves are at the same depth * No. of nodes and height A complete binary tree with N nodes has height O(logN) A complete binary tree with height d has, in total, 2 d+1 -1 nodes heightno. of nodes d 2d2d

Proof: O(logN) Height  Proof: a complete binary tree with N nodes has height of O(logN) 1. Prove by induction that number of nodes at depth d is 2 d 2. Total number of nodes of a complete binary tree of depth d is …… 2 d = 2 d Thus 2 d = N 4. d = log(N+1)-1 = O(logN)  Side notes: the largest depth of a binary tree of N nodes is O(N)

(Binary) Heap * Heaps are “almost complete binary trees” n All levels are full except possibly the lowest level n If the lowest level is not full, then nodes must be packed to the left Pack to the left

* Heap-order property: the value at each node is less than or equal to the values at both its descendants --- Min Heap  It is easy (both conceptually and practically) to perform insert and deleteMin in heap if the heap-order property is maintained A heap Not a heap

* Structure properties Has 2 h to 2 h+1 -1 nodes with height h n The structure is so regular, it can be represented in an array and no links are necessary !!! * Use of binary heap is so common for priority queue implemen- tations, thus the word heap is usually assumed to be the implementation of the data structure

Heap Properties Heap supports the following operations efficiently n Insert in O(logN) time n Locate the current minimum in O(1) time n Delete the current minimum in O(log N) time

Array Implementation of Binary Heap  For any element in array position i The left child is in position 2i The right child is in position 2i+1 The parent is in position floor(i/2) * A possible problem: an estimate of the maximum heap size is required in advance (but normally we can resize if needed) * Note: we will draw the heaps as trees, with the implication that an actual implementation will use simple arrays * Side notes: it’s not wise to store normal binary trees in arrays, because it may generate many holes A BC DEFG HIJ A B C D E F G HIJ …

Insertion * Algorithm 1. Add the new element to the next available position at the lowest level 2. Restore the min-heap property if violated  General strategy is percolate up (or bubble up): if the parent of the element is larger than the element, then interchange the parent and child Insert Percolate up to maintain the heap property swap

Insertion Complexity A heap! Time Complexity = O(height) = O(logN)

deleteMin: First Attempt * Algorithm 1. Delete the root. 2. Compare the two children of the root 3. Make the lesser of the two the root. 4. An empty spot is created. 5. Bring the lesser of the two children of the empty spot to the empty spot. 6. A new empty spot is created. 7. Continue

Example for First Attempt Heap property is preserved, but completeness is not preserved!

deleteMin 1. Copy the last number to the root (i.e. overwrite the minimum element stored there) 2. Restore the min-heap property by percolate down (or bubble down)

An Implementation Trick (see Weiss book) * Implementation of percolation in the insert routine n by performing repeated swaps: 3 assignment state-ments for a swap. 3d assignments if an element is percolated up d levels n An enhancement: Hole digging with d+1 assignments (avoiding swapping!) Dig a hole Compare 4 with Compare 4 with Compare 4 with 7

deleteMin with ‘Hole Trick’ create hole tmp = 6 (last element) Compare children and tmp bubble down if necessary Continue step 2 until reaches lowest level Fill the hole The same ‘hole’ trick used in insertion can be used here too

Heapsort (1) Build a binary heap of N elements n the minimum element is at the top of the heap (2) Perform N DeleteMin operations n the elements are extracted in sorted order (3) Record these elements in a second array and then copy the array back

Build Heap * Input: N elements * Output: A heap with heap-order property * Method 1: obviously, N successive insertions  Complexity: O(NlogN) worst case

Heapsort – Running Time Analysis (1) Build a binary heap of N elements n repeatedly insert N elements  O(N log N) time (there is a more efficient way, check textbook p223 if interested) (2) Perform N DeleteMin operations Each DeleteMin operation takes O(log N)  O(N log N) (3) Record these elements in a second array and then copy the array back n O(N) * Total time complexity: O(N log N) * Memory requirement: uses an extra array, O(N)

Heapsort: in-place, no extra storage * Observation: after each deleteMin, the size of heap shrinks by 1 n We can use the last cell just freed up to store the element that was just deleted  after the last deleteMin, the array will contain the elements in decreasing sorted order * To sort the elements in the decreasing order, use a min heap * To sort the elements in the increasing order, use a max heap n the parent has a larger element than the child

Sort in increasing order: use max heap Delete 97

Delete 16 Delete 14 Delete 10 Delete 9Delete 8

Priority Queue: Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job A – 100 pages Job B – 10 pages Job C -- 1 page Average waiting time with FIFO service: ( ) / 3 = 107 time units Average waiting time for shortest-job-first service: ( ) / 3 = 41 time units A queue be capable to insert and deletemin ? Priority Queue

* Priority queue is a data structure which allows at least two operations n insert deleteMin : finds, returns and removes the minimum elements in the priority queue * Applications: external sorting, greedy algorithms Priority Queue deleteMininsert

Possible Implementations * Linked list n Insert in O(1) n Find the minimum element in O(n), thus deleteMin is O(n) * Binary search tree (AVL tree, to be covered later) n Insert in O(log n) n Delete in O(log n) n Search tree is an overkill as it does many other operations * Eerr, neither fit quite well…