Download presentation

Presentation is loading. Please wait.

Published byCarli Kindall Modified over 2 years ago

1
Design and Analysis of Algorithms Heapsort Haidong Xue Summer 2012, at GSU

2
Max-Heap A complete binary tree, and … Yes No every level is completely filled, except possibly the last, which is filled from left to right

3
Max-Heap Satisfy max-heap property: parent >= children 16 1410 8793 2 Since it is a complete tree, it can be put into an array without lose its structure information.

4
Max-Heap 16 1410 8793 2 123 4 5 6 78

5
Max-Heap Use an array as a heap 16 1410 8793 2 123 4 5 6 78 16 14 10 8 7932 1 23 456 7 8 For element at i: Parent index =parent(i)= floor(i/2); Left child index = left(i)=2*i; Right child index =right(i)=2*i +1 Last non-leaf node = floor(length/2) i=3 2*i = 6 2*i+1=7 floor(i/2)=floor(1.5)=1 floor(length/2)=4

6
Max-Heapify Input: A compete binary tree rooted at i, whose left and right sub trees are max-heaps; last node index Output: A max-heap rooted at i. Algorithm: 1. Choose the largest node among node i, left(i), right(i). 2. if(the largest node is not i){ – Exchange i with the largest node – Max-Heapify the affected subtree }

7
Max-Heapify Example 2 1610 14793 8

8
Heapsort for a heap Input: a heap A Output: a sorted array A Algorithm: 1. Last node index l = A’s last node index 2. From the last element to the second{ exchange (current, root); l--; Max-Heapify(A, root, l); }

9
Heapsort example 16 1410 87 9 3 2

10
Heapsort example 14 810 27 9 3 16

11
Heapsort example 10 89 27 3 14 16

12
Heapsort example 9 83 27 10 14 16

13
Heapsort example 8 73 29 10 14 16

14
Heapsort example 7 23 89 10 14 16

15
Heapsort example 3 27 89 10 14 16

16
Array -> Max-Heap Input: a array A Output: a Max-Heap A Algorithm: Considering A as a complete binary tree, from the last non-leaf node to the first one{ Max-Heapify(A, current index, last index); }

17
Build Heap Example 16 14 10 8 7 14 8 16 107

18
Heapsort Input: array A Output: sorted array A Algorithm: 1. Build-Max-Heap(A) 2. Last node index l = A’s last node index 3. From the last element to the second{ exchange (current, root); l--; Max-Heapify(A, root, l); } Let’s try it

19
Analysis of Heapsort Input: array A Output: sorted array A Algorithm: 1. Build-Max-Heap(A) 2. Last node index l = A’s last node index 3. From the last element to the second{ exchange (current, root); l--; Max-Heapify(A, root, l); } O(n) or O(nlgn) O(nlgn) O(n)

Similar presentations

OK

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 19: Heap Sort.

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 19: Heap Sort.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google