Binary Heaps Text Read Weiss, § Binary Heap One-array representation of a tree Complete trees Building a Binary Heap Insert Delete
Motivation Development of a data structure which allows efficient inserts and efficient deletes of the minimum value (minheap) or maximum value (maxheap)
Implementation One-array implementation of a binary tree Root of tree is at element 1 of the array If a node is at element i of the array, then its children are at elements 2*i and 2*i+1 If a node is at element i of the array, then its parent is at element floor(i/2)= └ i/2 ┘
Implementation i array __ __ __ __ currentsize = 12
Implementatation Heap must be a complete tree all leaves are on the lowest two levels nodes are added on the lowest level, from left to right nodes are removed from the lowest level, from right to left
Inserting a Value i array __ __ __ currentsize = 13 Insert 3 3 insert here to keep tree complete
Inserting a Value Insert 3 save new value in a temporary location: tmp 3
Inserting a Value Insert 3 14 tmp 3 copy 14 down because 14 > 3
Inserting a Value Insert 3 14 tmp 3 copy 12 down because 12 > 3
Inserting a Value Insert 3 14 tmp 3 copy 4 down because 4 > 3
Inserting a Value Insert 3 14 insert 3
Heap After Insert
Deleting a Value (note new tree!) Delete 3
Deleting a Value Delete 3 3 save root value … tmp
Deleting a Value Delete 3 3 tmp X copy value of last node in complete tree into temporary location; decrement currentsize 14
Deleting a Value Delete 3 3 tmp push down root … compare children select smaller 14
Deleting a Value Delete 3 3 tmp push down root … copy smaller value into parent 14
Deleting a Value Delete 3 3 tmp push down root … 14 compare children select smaller (25)
Deleting a Value Delete 3 3 tmp push down root … copy 14 into parent because 14 < smaller child
Deleting a Value Delete 3 3 return