100 likes | 148 Views
Learn about max heap data structure, its implementation using arrays, insertion, deletion operations, and practical exercises to understand heap concepts thoroughly.
E N D
Heaps • ICS 211: Introduction to Computer Science II • William Albritton • Information and Computer Sciences Department at the University of Hawai‘i at Mānoa • "Heavier-than-air flying machines are impossible." • Lord Kelvin, president, Royal Society, 1895 © 2007 William Albritton
Terminology • Heap • A complete binary tree, in which each node has a greater (or equal) priority value than its children • A more accurate name for this is max heap • If each node has a priority value less than its children, it is called a min heap © 2007 William Albritton
Class Exercise • Is this a max heap or a min heap? • Created by Onar Vikingstad 2005, from Wikipedia “Heap (data structure)” © 2007 William Albritton
Heap Array Implementation • Since a heap is a complete binary tree, it is convenient to implement with an array • Next node that is added is put at end of array • If the parent node has array index i • Then left child is at index 2*i+1 • And right child is at index 2*i+2 • If left or right child has array index i • Then parent is at index (i-1)/2 © 2007 William Albritton
Class Exercise • Convert this tree representation of a heap into the corresponding array representation • Created by Onar Vikingstad 2005, from Wikipedia “Heap (data structure)” © 2007 William Albritton
Class Exercise • Do the the following arrays represent a max heap, a min heap, or neither? • Index: 0 1 2 3 4 5 6 7 8 9 • Values: 0 1 2 0 4 5 6 7 8 9 • Values: 9 8 7 6 5 4 3 2 1 0 • Values: 5 5 5 6 6 6 6 7 7 1 • Values: 9 3 9 2 1 6 7 1 2 1 • Values: 8 7 6 1 2 3 4 2 1 2 © 2007 William Albritton
Max Heap Insertion • To keep the tree complete, the new node is inserted at bottom right position in tree • This corresponds to the end of array • To keep the node relationship of the heap intact, the new node is swapped with its parent, until the parent node is larger than the child node (“trickles up”) • Each node in a heap has a larger value than its two child nodes © 2007 William Albritton
Max Heap Deletion • Since the largest node is at the top of the heap, it is deleted and its value returned • “Deletion” means that it is replaced with the rightmost, bottommost node • This maintains the heap as a complete binary tree • To keep largest value at top of tree, the new value must be compared to its children • If it is smaller than its largest child node, it is swapped with its largest child node • “Trickles down” © 2007 William Albritton
Class Exercise • Insert the following values into a max heap • 5, 4, 6, 3, 3, 8, 8, 4, 5, 6 • Delete from the same heap 5 times • Redraw the heap each time • What are the return values for each delete? © 2007 William Albritton