Objective • O(n lg n) worst case like merge sort. • Sorts in place like insertion sort. • A heap can be stored as an array A. • Root of tree is A[1]. • Parent of A[i ] = A[i/2]. • Left child of A[i ] = A[2 i ]. • Right child of A[i ] = A[2 i + 1]. • Computing is fast with binary representation implementation.
Heap data structure Heap is a nearly complete binary tree. “Heap is almostcomplete binary tree. ” Height of node = # of edges on a longest simple path from the node down to a leaf. Height of heap = height of root = (lg n). Computer Sciences 4
Maintaining the heap property Computer Sciences 5
Building a heap (a bottom-up manner) Computer Sciences 6
The heap-sort algorithm Computer Sciences 7
Exercises Illustrate the operation of heap. Sort on the below array: {17, 1, 9, 14, 2, 8, 3} 1 17 17 1 4 14 2 3 5 6 2 8 9 1 7 3 14 Computer Sciences a) 9 8 8 2 b) 3