Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.

Slides:



Advertisements
Similar presentations
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Advertisements

Heapsort By: Steven Huang. What is a Heapsort? Heapsort is a comparison-based sorting algorithm to create a sorted array (or list) Part of the selection.
Heapsort.
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.
Heapsort. 2 Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n) Quicksort.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 19: Heap Sort.
C++ Plus Data Structures
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
QuickSort QuickSort is often called Partition Sort. It is a recursive method, in which the unsorted array is first rearranged so that there is some record,
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
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.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Heapsort CSC Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n)
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.
Data Structure & Algorithm II.  Delete-min  Building a heap in O(n) time  Heap Sort.
data ordered along paths from root to leaf
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.
Lecture 8COMPSCI.220.FS.T Algorithm HeapSort J. W. J. Williams (1964): a special binary tree called heap to obtain an O(n log n) worst-case sorting.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
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.
David Luebke 1 12/23/2015 Heaps & Priority Queues.
Heaps and Heapsort Prof. Sin-Min Lee Department of Computer Science San Jose State University.
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.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Heaps & Priority Queues
Lecture 8 : Priority Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
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:
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 and Heaps Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
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)
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
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.
Sorting Cont. Quick Sort As the name implies quicksort is the fastest known sorting algorithm in practice. Quick-sort is a randomized sorting algorithm.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
"Teachers open the door, but you must enter by yourself. "
Bohyung Han CSE, POSTECH
Heap Sort Example Qamar Abbas.
Design and Analysis of Algorithms
7/23/2009 Many thanks to David Sun for some of the included slides!
Heapsort Heap & Priority Queue.
Dr. David Matuszek Heapsort Dr. David Matuszek
Draw pictures to indicate the subproblems middleMax solves at each level and the resulting maxPtr and PrevPtr for each on this linked list:
i206: Lecture 14: Heaps, Graphs intro.
Binary Tree Application Operations in Heaps
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Computer Science 2 Heaps.
"Teachers open the door, but you must enter by yourself. "
C++ Plus Data Structures
Heapsort.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
HEAPS.
Heapsort.
CSE 373, Copyright S. Tanimoto, 2002 Priority Queues -
Heaps By JJ Shepherd.
Heapsort.
Heapsort.
CO 303 Algorithm Analysis and Design
Heaps.
Presentation transcript:

Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus Data Structure textbook slides

What is a Heap?  Shape: complete binary tree  Order: for each node in the heap, the value stored in that node is greater than or equal to the value in each of its children. —Root always has the largest element  By default, when we say “heap”, we mean “maximum heap” —minimum heap: for each node in the heap, the value stored in that node is less than or equal to the value in each of its children

Are these Heaps? C A T treePtr

Are these Heaps?

Store a Heap in Array tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes For any tree node nodes[index] left child: nodes[index*2 + 1] right child: nodes[index*2 + 2] parent: nodes[(index – 1)/2]

Construct a Heap  How to guarantee it is a complete binary tree? —treat the data as an array/sequence, add nodes to the tree in a top-down, left-to-right manner  How to guarantee the order? —bubble the values as high as it can go

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] nodes 10 Add nodes[0] to the tree: it has no parent, so we have a heap.

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[1] to the tree: 20 > 10, so we need to bubble 20 up. Exchange 20 and 10 in both the tree and the array.

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[1] to the tree: now we have a heap.

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[2] to the tree: 12 < 20. It cannot go higher. We have a heap. 12

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[3] to the tree: 40 < 10. We need to bubble 40 up. Exchange 40 and 10 in both tree and array

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[3] to the tree: 40 < 20. We need to bubble 40 up. Exchange 40 and 20 in both tree and array

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[3] to the tree: 40 cannot go higher. We have a heap

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[4] to the tree: 20 = 20. It cannot go higher. We have a heap

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[5] to the tree: 15 < 12. We need to bubble 15 up. Exchange 15 and 12 in both tree and array

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[5] to the tree: 15 < 12. We need to bubble 15 up. Exchange 15 and 12 in both tree and array

Example: Done! [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Add nodes[5] to the tree: 15 cannot go higher. We have a heap. All nodes are added. Done!

Construct a Heap: Bubble Up Algorithm  Given nodes[] and size  For each node at index i: —Leaf = i; Done = false —while Leaf is not 0 AND Done == false  Parent = (Leaf-1)/2  if nodes[Leaf] > nodes[Parent] Swap nodes[Leaf] and nodes[Parent] Leaf = Parent;  otherwise Done = true  What is the time complexity? O(nlog 2 n)

ReheapUp Algorithm  Based on the previous algorithm.  What if we want to add a new item to an existing heap? —add the item as the last element in the array  it is the only item that violates the order —restore the order in a bottom-up manner —we can do it recursively! void ReheapUp( int root, int bottom ) { int parent ; if ( bottom > root ){ parent = ( bottom - 1 ) / 2; if ( nodes [ parent ] < nodes [ bottom ] ){ Swap ( nodes [ parent ], nodes [ bottom ] ); ReheapUp ( root, parent ); }

Sorting Using Heap  Heap is perfect for sorting: the root is always the largest!  Basic algorithm: —use heap in which top node contains largest value —repeat until heap is empty:  take root (largest value) off heap, put it in its place  reconstruct the heap  How to reconstruct the heap?

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Take root off heap

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes 20 Put the last one in the array (12) as the new root: Only the root violates the order. Its left and right subtrees are still heaps! We also have space to store the old root What should we put here?

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes < 20 and 12 < 15 Swap 12 with its child: which one? The larger one so that we guarantee the new parent >= both children

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes < 20: Swap 12 with

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes < 20: Swap 12 with 20 It is already a leaf node. We stop

ReheapDown Algorithm  To facilitate heapSort.  Root is the only node that violates the order: —reorder the heap by pushing down the root as low as possible  This procedure is also known as Heapify.  How to use Heapify to remove a node? ReheapDown ( root, bottom ) maxChild = index of the larger child of nodes[root] if nodes[root] < nodes[maxChild] Swap( nodes[root], nodes[maxChild] ReheapDown( maxChild, bottom )

Example: Continued [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes 20 Swap the root (20) and bottom (12) Remove 20 from the heap

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes ReheapDown 15 10

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Swap the root (20) and bottom (10). It is a heap now. Remove 20 from the heap 15 10

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes ReheapDown 15

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Swap the root (15) and bottom (10) Remove 15 from the heap 10

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Reheap

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Swap the root (12) and bottom (10) Remove 12 from the heap

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes 10 We have only one node in the heap. Simply remove 10 from the heap and we are done!

Example: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Note that now the array is sorted in ascending order! This is called Heap Sort!

Heap Sort  Algorithm: 1.Construct a heap H of n nodes 2.for i: length(H)-1 to 1 1. Swap H[0] and H[i] 2. Reduce H’s size by 1 3. ReheapDown( 0, i - 1 ) What is the time complexity?  Construct a heap using ReheapUp takes O(nlog 2 n)  ReheapDown takes O(log 2 n) which repeats n-1 times  O(nlog 2 n)

A Better Algorithm to Construct a Heap  Inspired by the Heapify process, we have another algorithm to build a heap:  How to guarantee it is a complete binary tree? —treat the data as an array/sequence, and convert it into a complete binary tree in a top-down, left-to-right manner  How to guarantee the order? —Leaf nodes are already heaps (single node) —Starting from the first non-leaf node till the root, make sure each node is larger than its children  if not, do ReheapDown

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Leaf nodes are already heaps. So we start from Level 1: ReheapDown( 2, 5);

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes ReheapDown( 1, 5);

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes ReheapDown( 0, 5);

Example [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes Now we have a heap!

Construct a Heap by Heapify  Algorithm: 1.Elements are stored in array A 2.for i: from (size(A)/2 – 1) to 0 1. ReheapDown( i, size(A)-1)  What is the time complexity? O(n) !!!

Why O(n) to build a heap?  Assume it is a full tree.  Total work to build a heap is:  Since, we can get  So we have T(n) = 2 h+1  Since h = log 2 n, we have T(n) = n+1  O(n)

Summary  Insert a new item to a heap: —The last element violates the order —Use ReheapUp algorithm  Heap Sort: —Keep taking off the root which is the largest —replace the root with the last element in the heap —The new root violates the order —Use ReheapDown algorithm —O(nlog 2 n)  Build a heap: —by ReheapUp: O(nlog 2 n) —by ReheapDown: O(n)