Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on MinHeap: Insert Delete Converting an array.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
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.
Chapter 15 Heaps. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a heap abstract data structure Demonstrate.
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.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
CS 206 Introduction to Computer Science II 11 / 04 / 2009 Instructor: Michael Eckmann.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Chapter 10 Heaps Anshuman Razdan Div of Computing Studies
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
1 Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
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.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Chapter 21 Binary Heap.
data ordered along paths from root to leaf
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
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.
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.
Heaps and Heapsort Prof. Sin-Min Lee Department of Computer Science San Jose State University.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
1 Heaps A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: –(i) efficient.
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.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
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.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
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.
Heaps A heap is a binary tree that satisfies the following properties: Structure property: It is a complete binary tree Heap-order property: Each node.
CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
CS 367 Introduction to Data Structures Lecture 8.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
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.
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)
Heaps (8.3) CSE 2011 Winter May 2018.
Priority Queues (Heaps)
Source: Muangsin / Weiss
Binary Heaps What is a Binary Heap?
CSCE 3100 Data Structures and Algorithm Analysis
Heaps, Heap Sort, and Priority Queues
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
- Alan Perlis Heaps "You think you know when you can learn,
CSCI2100 Data Structures Tutorial 7
Heaps, Heap Sort, and Priority Queues
Binary Heaps Priority Queues
Priority Queues.
CMSC 341 Lecture 14 Priority Queues & Heaps
Priority Queues.
Tree Representation Heap.
Binary Heaps Priority Queues
Priority Queues (Heaps)
Heaps.
Priority Queues (Heaps)
Presentation transcript:

Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on MinHeap: Insert Delete Converting an array into a binary heap Heap Applications: Heap Sort Heap as a priority queue

What is a Binary Heap? A binary heap is a complete binary tree with one or both of the following heap order properties: MinHeap property: Each node must have a key that is less or equal to the key of each of its children. MaxHeap property: Each node must have a key that is greater or equal to the key of each of its children. A binary heap satisfying the MinHeap property is called a MinHeap. A binary heap satisfying the MaxHeap property is called a MaxHeap. A binary heap with all keys equal is both a MinHeap and a MaxHeap. Recall: A complete binary tree may have missing nodes only on the right side of the lowest level. All levels except the bottom one must be fully populated with nodes All missing nodes, if any, must be on the right side of the lowest level

MinHeap and non-MinHeap examples A MinHeap Violates MinHeap property 21> Not a Heap Violates heap structural property Not a Heap Violates heap structural property Not a Heap

MaxHeap and non-MaxHeap examples A MaxHeap Violates MaxHeap property 65 < 67 Violates heap structural property Not a Heap Not a Heap Not a Heap

Array Representation of a Binary Heap A heap is a dynamic data structure that is represented and manipulated more efficiently using an array. Since a heap is a complete binary tree, its node values can be stored in an array, without any gaps, in a breadth-first order, where: Value(node i+1 ) array[ i ], for i > The root is array[0] The parent of array[i] is array[(i – 1)/2], where i > 0 The left child, if any, of array[i] is array[2i+1]. The right child, if any, of array[i] is array[2i+2].

Array Representation of a Binary Heap (contd.) We shall use an implementation in which the heap elements are stored in an array starting at index 1. Value(node i )array[i], for i > The root is array[1]. The parent of array[i] is array[i/2], where i > 1 The left child, if any, of array[i] is array[2i]. The right child, if any, of array[i] is array[2i+1].

MinHeap Implementation The class hierarchy for BinaryHeap is: MyComparable Container PriorityQueue AbstractObject AbstractContainer BinaryHeap The PriorityQueue interface is: 1 public interface PriorityQueue extends Container 2 { 3 public abstract void enqueue(MyComparable comparable) ; 4 public abstract MyComparable findMin() ; 5 public abstract MyComparable dequeueMin() ; 6 }

MinHeap Implementation (contd.) 1 public class BinaryHeap extends AbstractContainer implements PriorityQueue 2 { 3 protected MyComparable array[] ; 4 // count is inherited from AbstractContainer 5 public BinaryHeap(int size) 6 { 7 array = new MyComparable[size + 1] ; // array[0] is not used 8 } 9 10 public BinaryHeap(MyComparable[ ] comparable) 11 { 12 this(comparable.length) ; for(int i = 0 ; i < comparable.length ; i++) 15 array[i + 1] = comparable[i] ; 16 count = comparable.length ; 17 buildHeapBottomUp() ; 18 } 19 // }

MinHeap Insertion The pseudo code algorithm for inserting in a MinHeap is: 1 minHeapInsert(e1) 2 { 3 if(Heap is full) throw an exception ; 4 insert e1 at the end of the heap ; 5 while(e1 is not in the root node and e1 < parent(e1)) 6 swap(e1, parent(e1)) ; 7} The process of swapping an element with its parent, in order to restore the heap order property after an insertion is called percolate up, sift up, or reheapification upward. Thus, the steps for insertion are: 1.Insert at the end of the heap. 2.As long as the heap order property is violated, percolate up.

Percolate-Up Via a Hole Instead of repeated swappings, it is more efficient to use a hole (i.e., an empty node) to percolate up: To insert an element e, insert a hole at the end of the heap. While the heap order property is violated, percolate the hole up. Insert e in the hole. p hole e e p p e p < e p > e

MinHeap Insertion Example Insert Percolate up Percolate up

MinHeap Insertion implementation 1public void enqueue(MyComparable comparable) 2{ 3 if(isFull()) throw new ContainerFullException() ; 4 // percolate up via a hole 5 int hole = ++count ; 6 while(hole > 1 && array[hole / 2].isGT(comparable)) 7 { 8 array[hole] = array[hole / 2] ; 9 hole = hole / 2 ; 10 } 11 array[hole] = comparable ; 12 } 1public boolean isFull() 2{ 3 return count == array.length - 1 ; 4 }

MinHeap deletion The pseudo code algorithm for deleting from a MinHeap is: 1 minHeapDelete(){ 2 if(Heap is empty) throw an exception ; 3 extract the element from the root ; 4 if(root is a leaf node){ delete root ; return; } 5 copy the element from the last leaf to the root ; 6 delete last leaf ; 7 p = root ; 8 while(p is not a leaf node and p > any of its children) 9 swap p with the smaller child ; 10 return ; 11} The process of swapping an element with its smaller child, in order to restore the heap order property after a deletion is called percolate down, sift down, or reheapification downward. Thus, the steps for deletion are: 1.Replace the value at the root by the last leaf value. 2.Delete the last leaf. 3.As long as the heap order property is violated, percolate down.

Percolate-Down Via a Hole Instead of repeated swappings, it is more efficient to use a hole (i.e., an empty node) to percolate down: A hole is created in the root by deleting the root element. Copy the value in the last node in a temporary variable. Delete the last node. While the heap order property is violated, percolate the hole down. Insert the value from the temporary variable into the hole. l r r l l r l r e e < min(l, r) e > l < r e > l > r

MinHeap Deletion Example delete last node Delete min element Replace by value of last node Percolate down Percolate down

MinHeap Deletion Implementation 1 public MyComparable dequeueMin(){ 2 if(isEmpty()) throw new ContainerEmptyException(); 3 MyComparable minItem = array[1]; 4 array[1] = array[count]; 5 count--; 6 percolateDown(1); 7 return minItem; 8} 1 private void percolateDown(int hole) { 2 int child ; MyComparable temp = array[hole] ; 3 while(hole * 2 <= count) { 4 child = hole * 2 ; 5 if(child + 1 <= count && array[child + 1].isLT(array[child]) ) 6 child++ ; 7 if(array[child].isLT(temp)) 8 array[hole] = array[child] ; 9 else 10 break ; 11 hole = child ; 12 } 13 }

Converting an array into a Binary heap The algorithm to convert an array into a binary heap is: 1.Start at the level containing the last non-leaf node (i.e., array[n/2], where n is the array size). 2.Make the subtree rooted at the last non-leaf node into a heap by invoking percolateDown. 3.Move in the current level from right to left, making each subtree, rooted at each encountered node, into a heap by invoking percolateDown. 4.If the levels are not finished, move to a lower level then go to step 3. 5.Stop. The above algorithm can be refined to the following method of the BinaryHeap class: 1private void buildHeapBottomUp() 2{ 3 for(int i=count/2; i>=1; i--) 4 { 5 // restore heap property for subtree rooted at array[i] 6 percolateDown(i) ; 7 } 8 }

Converting an array into a MinHeap (Example) At each stage convert the highlighted tree into a MinHeap by percolating down starting at the root of the highlighted tree

Heap Application: Heap Sort A MinHeap or a MaxHeap can be used to implement an efficient sorting algorithm called Heap Sort. The following algorithm uses a MinHeap: 1 public static void heapSort(MyComparable[] array) 2 { 3 BinaryHeap heap = new BinaryHeap(array) ; 4 for(int i = 0; i < array.length; i++) 5 array[i] = heap.dequeueMin() ; 6 } Because the dequeueMin algorithm is O(log n), heapSort is an O(n log n) algorithm. Apart from needing the extra storage for the heap, heapSort is among efficient sorting algorithms.

Heap Applications: Priority Queue A heap can be used as the underlying implementation of a priority queue. A priority queue is a data structure in which the items to be inserted have associated priorities. Items are withdrawn from a priority queue in order of their priorities, starting with the highest priority item first. Priority queues are often used in resource management, simulations, and in the implementation of some algorithms (e.g., some graph algorithms, some backtracking algorithms). Several data structures can be used to implement priority queues. Below is a comparison of some: Dequeue MinFind MinEnqueueData structure O(n) O(1)Unsorted List O(1) O(n)Sorted List O(log n) AVL Tree O(log n)O(1)O(log n)MinHeap

Priority Queue (Contd.) 1 priorityQueueEnque(e1) 2 { 3 if(priorityQueue is full) throw an exception; 4 insert e1 at the end of the priorityQueue; 5 while(e1 is not in the root node and e1 < parent(e1)) 6 swap(e1, parent(e1)); 7 } 1 priorityQueueDequeue(){ 2 if(priorityQueue is empty) throw an exception; 3 extract the highest priority element from the root; 4 if(root is a leaf node){ delete root ; return; } 5 copy the element from the last leaf to the root; 6 delete last leaf; 7 p = root; 8 while(p is not a leaf node and p > any of its children) 9 swap p with the smaller child; 10 return; 11 } X Heap X is the element with highest priority