S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES 20-21 Priority Queues and Binary Heaps Algorithms.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

BY Lecturer: Aisha Dawood. Heapsort  O(n log n) worst case like merge sort.  Sorts in place like insertion sort.  Combines the best of both algorithms.
Analysis of Algorithms
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
September 19, Algorithms and Data Structures Lecture IV Simonas Šaltenis Nykredit Center for Database Research Aalborg University
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
CS 253: Algorithms Chapter 6 Heapsort Appendix B.5 Credit: Dr. George Bebis.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Analysis of Algorithms CS 477/677
Tirgul 4 Sorting: – Quicksort – Average vs. Randomized – Bucket Sort Heaps – Overview – Heapify – Build-Heap.
Comp 122, Spring 2004 Heapsort. heapsort - 2 Lin / Devi Comp 122 Heapsort  Combines the better attributes of merge sort and insertion sort. »Like merge.
Data Structures, Spring 2004 © L. Joskowicz 1 Data Structures – LECTURE 7 Heapsort and priority queues Motivation Heaps Building and maintaining heaps.
Heapsort Chapter 6. Heaps A data structure with  Nearly complete binary tree  Heap property: A[parent(i)] ≥ A[i] eg. Parent(i) { return } Left(i) {
1 Priority Queues A priority queue is an ADT where: –Each element has an associated priority –Efficient extraction of the highest-priority element is supported.
Tirgul 7 Heaps & Priority Queues Reminder Examples Hash Tables Reminder Examples.
David Luebke 1 7/2/2015 Merge Sort Solving Recurrences The Master Theorem.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
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.
Sorting Algorithms (Part II) Slightly modified definition of the sorting problem: input: A collection of n data items where data item a i has a key, k.
2IL50 Data Structures Spring 2015 Lecture 3: Heaps.
Ch. 6: Heapsort n nodes. Heap -- Nearly binary tree of these n nodes (not just leaves) Heap property If max-heap, the max-heap property is that for every.
David Luebke 1 10/3/2015 CS 332: Algorithms Solving Recurrences Continued The Master Theorem Introduction to heapsort.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Heaps, Heapsort, Priority Queues. Sorting So Far Heap: Data structure and associated algorithms, Not garbage collection context.
Binary Heap.
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.
2IL50 Data Structures Fall 2015 Lecture 3: Heaps.
Data Structure & Algorithm II.  Delete-min  Building a heap in O(n) time  Heap Sort.
Heaps. What is a heap? Like a binary search tree, but less structure within each level. Guarantees: – Parent better than child – That’s it! What does.
David Luebke 1 6/3/2016 CS 332: Algorithms Heapsort Priority Queues Quicksort.
S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES Binary Search Trees Algorithms and Data Structures.
Data Structure & Algorithm II.  In a multiuser computer system, multiple users submit jobs to run on a single processor.  We assume that the time required.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 9.
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:
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.
Data Structure II So Pak Yeung Outline Review  Array  Sorted Array  Linked List Binary Search Tree Heap Hash Table.
1 Analysis of Algorithms Chapter - 03 Sorting Algorithms.
1 Algorithms CSCI 235, Fall 2015 Lecture 14 Analysis of Heap Sort.
David Luebke 1 12/23/2015 Heaps & Priority Queues.
Computer Algorithms Lecture 9 Heapsort Ch. 6, App. B.5 Some of these slides are courtesy of D. Plaisted et al, UNC and M. Nicolescu, UNR.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
ΔΟΜΕΣ ΔΕΔΟΜΕΝΩΝ & ΑΡΧΕΙΩΝ
CSC 413/513: Intro to Algorithms Solving Recurrences Continued The Master Theorem Introduction to heapsort.
Chapter 6: Heapsort Combines the good qualities of insertion sort (sort in place) and merge sort (speed) Based on a data structure called a “binary heap”
Heaps and basic data structures David Kauchak cs161 Summer 2009.
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:
Mergeable Heaps David Kauchak cs302 Spring Admin Homework 7?
David Luebke 1 2/5/2016 CS 332: Algorithms Introduction to heapsort.
Analysis of Algorithms CS 477/677 Lecture 8 Instructor: Monica Nicolescu.
CS6045: Advanced Algorithms Sorting Algorithms. Heap Data Structure A heap (nearly complete binary tree) can be stored as an array A –Root of tree is.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
Sept Heapsort What is a heap? Max-heap? Min-heap? Maintenance of Max-heaps -MaxHeapify -BuildMaxHeap Heapsort -Heapsort -Analysis Priority queues.
Heapsort Lecture 4 Asst. Prof. Dr. İlker Kocabaş.
6.Heapsort. Computer Theory Lab. Chapter 6P.2 Why sorting 1. Sometimes the need to sort information is inherent in a application. 2. Algorithms often.
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.
Priority Queues A priority queue is an ADT where:
"Teachers open the door, but you must enter by yourself. "
Heaps, Heapsort, and Priority Queues
Heaps, Heap Sort and Priority Queues
Heapsort.
Introduction to Algorithms
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
CS200: Algorithm Analysis
Ch 6: Heapsort Ming-Te Chi
"Teachers open the door, but you must enter by yourself. "
Topic 5: Heap data structure heap sort Priority queue
HEAPS.
Heapsort Sorting in place
Computer Algorithms CISC4080 CIS, Fordham Univ.
Presentation transcript:

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES Priority Queues and Binary Heaps Algorithms and Data Structures CMPSC 465

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 2 Trees Rooted Tree: collection of nodes and edges  Edges go down from root (from parents to children)  No two paths to the same node  Sometimes, children have “ names ” (e.g. left, right, middle, etc)

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. Where are trees useful? Some important applications  Parse trees (compilers)  Heaps  Search trees  String search  Game trees (e.g. chess program) E.g. parse tree for 3*(4+2)*(2^6)*( 8/3) ^ 2683 / *

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 4 Priority Queue ADT Dynamic set of pairs (key, data), called elements Supports operations:  MakeNewPQ ()  Insert ( S,x ) where S is a PQ and x is a (key,data) pair  Extract-Max ( S ) removes and returns the element with the highest key value (or one of them if several have the same value) Example: managing jobs on a processor, want to execute job in queue with the highest priority Can also get a “ min ” version, that supports Extract-Min instead of Extract-Max Sometimes support additional operations like Delete, Increase-Key, Decrease-Key, etc.

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 5 Heaps: Tree Structure Data Structure that implements Priority Queue  Conceptually: binary tree  In memory: (often) stored in an array Recall: complete binary tree  all leaves at the same level, and  every internal node has exactly 2 children Heaps are nearly complete binary trees  Every level except possibly the bottom one is full  Bottom layer is filled left to right

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 6 Height Heap Height =  length of longest simple path from root to some leaf  e.g. a one-node heap has height 0, a two- or three-node heap has height 1,... Exercises:  What is are max. and min. number of elements in a heap of height h? ans: min = 2 h, max = 2 h  What is height as a function of number of nodes n? ans: floor( log(n) )

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 7 Array representation Instead of dynamically allocated tree, heaps often represented in a fixed-size array  smaller constants, works well in hardware. Idea: store elements of tree layer by layer, top to bottom, left to right Navigate tree by calculating positions of neighboring nodes:  Left(i) := 2i  Right(i) := 2i+1  Parent(i) := floor(i/2) Example: [ ]

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 8 Review Questions Is the following a valid max-heap?   (If not, repair it to make it valid) Is an array sorted in decreasing order a valid max- heap?

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 9 Local Repair: Heapify “Down” Two important “ local repair operations ” :  Heapify “Down”, Heapify “ Up ” Suppose we start from a valid heap and decrease the key of node i, so  it is still smaller than parent  the two subtrees rooted at i remain valid How do we rearrange nodes to make the heap valid again?  Idea: let new, smaller key “ sink ” to correct position Find index with largest key among { i, Left( i ), Right( i )} If i != largest, EXCHANGE i with largest and recurse on largest

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 10 Local Repair: Heapify “Down” Pseudocode in book Running time: O(height) = O(log n)  Tight in worst case Correctness: by induction on height

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 11 MAX-HEAPIFY(-DOWN) Exercise: what does Max-Heapify do on the following input?  This gives us our first PQ operation: Extract-Max(A) 1. tmp := A[1] 2. A[1] := A[heap-size] 3. heap-size := heap-size-1 4. MAX-HEAPIFY-DOWN(A,1)  return tmp

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 12 Local Repair: Heapify “Up” Two important “ local repair operations ”  Heapify “ Down ”  Heapify “Up” Suppose we start from a valid heap and increase the key of node i, so  it is still larger than both children, but  might be larger than parent How do we rearrange nodes to make the heap valid again?  Idea: let new, larger key “ float ” to right position If A[i] > A[Parent(i)], EXCHANGE i with parent and recurse on parent Pseudocode in CLRS Chap 6.2: “ MAX-HEAPIFY ”

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 13 Local Repair: Heapify “Up” Pseudocode in book (see “ Increase-key ” ) Running time: O(log n)  tight in worst case Correctness: by induction on height

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 14 MAX-HEAPIFY(-UP) Exercise: what does Max-Heapify do on the following input?  This gives us our second PQ operation: Insert(A,x) 1. A[heap-size+1] := x 2. heap-size := heap-size+1 3. MAX-HEAPIFY-UP(A,heap-size)

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 15 Other PQ operations Max(S): return max element without extracting it Increase-Key(S,i,new-key) Decrease-Key(S,i,new-key)  Both of these require knowing position of desired element  Can be taken care by “ augmenting ” using a dictionary data structure, such as hash table Delete(S,i)  Delete the element in position i

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 16 Heap Sort Heaps give an easy O(n log n) sorting algorithm:  For i=2 to n Insert(A,A[i])  For i= n downto 3 A[i] := Extract-Max(A) There is a faster way (O(n) time) to build a heap from an unsorted array.

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 17 Search Can we search for an element in a heap in sublinear (that is, o(n)) time, in the worst case? How would you prove that such a search algorithm does not exist?

S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. Heaps: Review Heap-leap-jeep-creep(A): 1. A.heap-size = 0 2. For i=1 to len(A) tmp = A[i] Heap-Insert(A,tmp) 3. For i=len(A) down to 1 tmp = Heap-Extract-Max(A) A[i]=tmp What does this do? What is the running time of this operation? 18