Beruflich Dokumente
Kultur Dokumente
National University
Page
Heap Sort
Heap sort uses a heap as described in the earlier lectures As we said before, a heap is a binary tree with the following two properties: Value of each node is not less than the values stored in each of its children The tree is perfectly balanced and the leaves in the level are all in the leftmost positions
National University
Page
Repeat the process for all elements until you are done
National University
Page
template <class T> void HeapSort(T data[ ], int size) { for (int i = (size/2)-1; i>=0; i--) MoveDown(data, i, size-1); // creates the heap for (i=size-1; i>=1; --i) { Swap (data[0], data[i]); // move the largest item to data[i] MoveDown(data, 0, i-1); // restores the heap } }
National University
Page
2 8 6 1 10 15 3 12 11
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University
2
8 1 12 11 10 15 6 3
Page
15
15
2 8 6 10 11 15 8
2 15 10 11 6
12 1
3 1
12
National University
Page
2 8 12 1
15 10
6 3 1 8
12
15 10
6 3
11
11
2 12 8 1 11 10 15 12 3 1 11 8 10
2 15
National University
Page
2 12 11 1 8 10 6 15 3 1 11 8 12 10
15 2 6 3
15 12 11 1 8 10 2 12 3 1 11 8 10
15 6
National University
Page
15 12 6 10 8 2
8 12 3
1 Restore the heap 12 6 10 15 2 3
11 1
11
11 8 1
A.R. Hadaegh Dr. Ahmad R. Hadaegh
6 10 2
15
National University Page 9
12 11 8
1 15 10 2 6 3 12 Restore the heap 8 15
1 11
10 2 6 3
11 10 8
12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
6 1 2 3
15
National University Page 10
Swap the root with the last element 11 10 8 12 15 1 2 6 3 12 Restore the heap 8 15
3 10
1 2 6 11
10 8 3
12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
6 1 2 11
15
National University Page 11
Swap the root with the last element 10 8 3 12 15 1 2 6 11 3 12 Restore the heap 15 8 1 10
2
6 11
8 3 2
12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
6 1 10 11
15
National University Page 12
1 3 2 12
15 12 Restore the heap 15 1 10 6 3 2 8 10 6 11
11
6 3 2
12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
1 8 10 11
15
National University Page 13
Swap the root with the last element 6 3 2 12 15 8 10 1 11 12 Restore the heap 3 2 6 12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
2 3 6 15 8 1
10
11
1 8 10 11
15
National University Page 14
3
2 6 12 15 8 10 1 11 12 Restore the heap 2 1 6 12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
1 2 6 15 8 10 3 11
3 8
10 11
15
National University Page 15
Swap the root with the last element 2 1 6 12 15 8 10 3 11 6 12 Restore the heap 1 15 2 8 10 1 3 11
2 6 12
A.R. Hadaegh Dr. Ahmad R. Hadaegh
3 8 10
11
15
National University Page 16
1 2 6 12 15 8 10 3 11
1 2 3 6
8
10 11 12 15
National University
Page 17