Heap Sort Example Qamar Abbas Why study Heapsort
Heap Sort Example Qamar Abbas
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 is usually O(n log n) but in the worst case slows to O(n 2) �Quicksort is generally faster, but Heapsort is better in time-critical applications �Heapsort is a really cool algorithm!
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 (or allow them to be garbage collected) when no longer needed 2. A balanced, left-justified binary tree in which no node has a value greater than the value in its parent � These two definitions have little in common � Heapsort uses the second definition
The Heap Data Structure �Def: A heap is a nearly complete binary tree with the following two properties: �Structural property: all levels are full, except possibly the last one, which is filled from left to right �Order (heap) property: for any node x Parent(x) ≥ x 8 7 5 4 2 Heap 4 It doesn’t matter that 4 in level 1 is smaller than 5 in level 2
Representation of Heaps � A heap can be stored as an array A. �Root of tree is A[1] �Left child of A[i] = A[2 i] �Right child of A[i] = A[2 i + 1] �Parent of A[i] = A[ i/2 ] �Heapsize[A] ≤ length[A] � The elements in the subarray A[( n/2 +1). . n] are leaves � The root is the maximum element of the heap A heap is a binary tree that is filled in order 5
The heap property �A node has the heap property if the value in the node is as large as or larger than the values in its children 12 8 12 3 Blue node has heap property 8 12 12 Blue node has heap property 8 14 Blue node does not have heap property �All leaf nodes automatically have the heap property �A binary tree is a heap if all nodes in it have the heap property
sift. Up � Given a node that does not have the heap property, you can give it the heap property by exchanging its value with the value of the larger child 12 8 14 14 Blue node does not have heap property 8 12 Blue node has heap property � This is sometimes called sifting up � Notice that the child may have lost the heap property
Operations on Heaps �Maintain the max-heap property �MAX-HEAPIFY �Create a max-heap from an unordered array �BUILD-MAX-HEAP �Sort an array in place �HEAPSORT �Priority queue operations 8
Constructing a heap �A tree consisting of a single node is automatically a heap �We construct a heap by adding nodes one at a time: �Add the node just to the right of the rightmost node in the deepest level �If the deepest level is full, start a new level �Examples: Add a new node here
Constructing a heap � Each time we add a node, we may destroy the heap property of its parent node � To fix this, we sift up � But each time we sift up, the value of the topmost node in the sift may increase, and this may destroy the heap property of its parent node � We repeat the sifting up process, moving up in the tree, until either �We reach nodes whose values don’t need to be swapped (because the parent is still larger than both children), or �We reach the root
Constructing a heap 8 8 10 10 8 1 12 8 5 2 10 8 10 3 10 5 12 8 12 5 10 8 5 4
Other children are not affected 12 10 8 12 5 14 14 8 14 5 10 12 8 5 10 � The node containing 8 is not affected because its parent gets larger, not smaller � The node containing 5 is not affected because its parent gets larger, not smaller � The node containing 8 is still not affected because, although its parent got smaller, its parent is still greater than it was originally
Heap Sort Example 25 22 17 19 11 14 Built Heap 25 22 19 17 11 14 15 15
Pass-1 Heap Sort Example 25 22 19 17 11 14 15
Pass-1 Heap Sort Example 25 22 19 17 11 14 15
Pass-1 Heap Sort Example 15 22 19 17 11 14
Pass-1 Heap Sort Example 22 15 19 17 11 14
Pass-1 Heap Sort Example 22 19 15 22 17 11 19 17 14 15 11 14 25
Pass-II Heap Sort Example 19 15 14 19 17 11 15 17 14 11 22 25
Pass-III Heap Sort Example 17 15 11 14 19 22 25
Pass-IV Heap Sort Example 15 14 11 11 17 19 22 25
Pass-V Heap Sort Example 14 11 15 17 19 22 25
Pass-V Heap Sort Example 11 11 14 15 17 19 22 25
Pass-VI Sorted Heap 11 14 15 17 19 22 25
Alg: HEAPSORT(A) 1. BUILD-MAX-HEAP(A) 2. for i ← length[A] downto 2 3. do exchange A[1] ↔ A[i] 4. MAX-HEAPIFY(A, 1, i - 1) � Running time: O(nlgn) 25 O(n) n-1 times O(lgn)
Example: MAX-HEAPIFY(A, 1, 4) A=[7, 4, 3, 1, 2] MAX-HEAPIFY(A, 1, 3) MAX-HEAPIFY(A, 1, 2) MAX-HEAPIFY(A, 1, 1) 26
HEAP-EXTRACT-MAX Alg: HEAP-EXTRACT-MAX(A, n) 1. if n < 1 2. then error “heap underflow” 3. max ← A[1] 4. A[1] ← A[n] 5. MAX-HEAPIFY(A, 1, n-1) remakes heap 6. return max 27
Example: HEAP-EXTRACT-MAX 16 14 7 4 max = 16 10 8 2 1 9 14 3 10 8 1 2 7 9 3 4 Heap size decreased with 1 14 Call MAX-HEAPIFY(A, 1, n-1) 8 4 2 28 10 7 1 9 3
Example: HEAP-EXTRACT-MAX 16 14 7 4 max = 16 10 8 2 1 9 14 3 10 8 1 2 7 9 3 4 Heap size decreased with 1 14 Call MAX-HEAPIFY(A, 1, n-1) 8 4 2 29 10 7 1 9 3
A sample heap � Here’s a sample binary tree after it has been heapified 25 22 19 18 17 22 14 21 14 3 9 15 11 � Notice that heapified does not mean sorted � Heapifying does not change the shape of the binary tree; this binary tree is balanced and left-justified because it started out that way
Removing the root � Notice that the largest number is now in the root � Suppose we discard the root: 11 22 19 18 17 22 14 21 14 3 9 15 11 � How can we fix the binary tree so it is once again balanced and left-justified? � Solution: remove the rightmost leaf at the deepest level and use it for the new root
The re. Heap method � Our tree is balanced and left-justified, but no longer a heap � However, only the root lacks the heap property 11 22 19 18 17 22 14 21 14 3 15 9 � We can sift. Up() the root � After doing this, one and only one of its children may have lost the heap property
The re. Heap method � Now the left child of the root (still the number 11) lacks the heap property 22 11 19 18 17 22 14 21 14 3 15 9 � We can sift. Up() this node � After doing this, one and only one of its children may have lost the heap property
The re. Heap method � Now the right child of the left child of the root (still the number 11) lacks the heap property: 22 22 19 18 17 11 14 21 14 3 15 9 � We can sift. Up() this node � After doing this, one and only one of its children may have lost the heap property —but it doesn’t, because it’s a leaf
The re. Heap method � Our tree is once again a heap, because every node in it has the heap property 22 22 19 18 17 21 14 11 14 3 15 9 � Once again, the largest (or a largest) value is in the root � We can repeat this process until the tree becomes empty � This produces a sequence of values in order largest to smallest
Heap insertion and Deletion �Both the insert and remove operations modify the heap to conform to the shape property first, by adding or removing from the end of the heap. Then the heap property is restored by traversing up or down the heap. Both operations take O(log n) time.
Heap Insert �Add the element to the bottom level of the heap. �Compare the added element with its parent; if they are in the correct order, stop. �If not, swap the element with its parent and return to the previous step. �The number of operations required is dependent on the amount of levels the new element must rise to satisfy the heap property, thus the insertion operation has a time complexity of O(log n). �As an example, say we have a max-heap
Heap Insert
Heap Insert �and we want to add the number 15 to the heap. We first place the 15 in the position marked by the X. However, the heap property is violated since 15 is greater than 8, so we need to swap the 15 and the 8. So, we have the heap looking as follows after the first swap:
Heap Insert �However the heap property is still violated since 15 is greater than 11, so we need to swap again:
Heap Delete �Replace the root of the heap with the last element on the last level. �Compare the new root with its children; if they are in the correct order, stop. �If not, swap the element with one of its children and return to the previous step. (Swap with its smaller child in a min-heap and its larger child in a max-heap. )
Heap Delete � if we have the same max-heap as before, we remove the 11 and replace it with the 4
Heap Delete �Now the heap property is violated since 8 is greater than 4. In this case, swapping the two elements, 4 and 8, is enough to restore the heap property and we need not swap elements further:
Max Heapify �Overview of the algorithm: �Inputs: Array A (or binary tree) index i in array �Precondition: �The binary trees rooted at LEFT(i) and RIGHT(i) are heaps �Note: A[i] may be smaller than its children �Postcondition: �The subtree rooted at index i is a heap
Max-Heapify � Max-Heapify (A, i): left ← 2 i right ← 2 i + 1 largest ← i � if left ≤ heap_length[A] and A[left] > A[largest] then: largest ← left � if right ≤ heap_length[A] and A[right] > A[largest] then: largest ← right � if largest ≠ i then: swap A[i] ↔ A[largest] Max-Heapify(A, largest)
- Slides: 45