Download presentation
Presentation is loading. Please wait.
Published byHenry Bradford Modified over 9 years ago
1
HEAPSORT The array A[1].. A[n] is sorted by treating the sub-array A[1].. A[p] as a heap: 1. Build A[1].. A[p] into a heap. 2. Exchange A[1] and A[p], so that A[p] is now the maximum element. Repeat 1 and 2 for p = n, n-1,..., 3, 2.
2
COMPLETE BINARY TREES A complete binary tree is a rooted binary tree in which each parent node has exactly two children and all the leaves are at the last level.
3
Complete Binary Trees Example Level 0 Level 1 Level 2 Level 3
4
ALMOST COMPLETE BINARY TREES An almost complete binary tree is a rooted binary tree with levels 0 to k, in which all nodes in levels 0 to (k-1) are present and only the rightmost nodes in level k may be absent. A complete binary tree is an almost complete binary tree.
5
Almost Complete Binary Trees Example Level 0 Level 1 Level 2 Level 3
6
HEAPS A heap is an almost complete binary tree in which each node x is assigned a value v(x) that satisfies the heap property: v(x) ≥ max { v(lchild(x)), v(rchild(x)) }
7
Heaps Example 100 15 100 98 75 85 99 50 74 8320 92
8
ARRAYS AS ALMOST COMPLETE BINARY TREES An array A[1].. A[n] can be treated as an almost complete binary tree, as follows: A[1] is the root; A[2] and A[3] are the children of A[1]; A[4] and A[5] are the children of A[2]; A[6] and A[7] are the children of A[3]; etc.
9
Arrays as Almost Complete Binary Trees Array elements as nodes A[3] A[7] A[1] A[2] A[4] A[5] A[6] A[8] A[9] A[10] A[11] A[12]
10
Arrays as Almost Complete Binary Trees Assume an array A[1].. A[n]. For a parent node at array index k: lchild(k) = 2 * k rchild(k) = 2 * k + 1 provided that 2*k ≤ n and 2*k+1 ≤ n. For a child node at array index k: parent(k) = k/2
11
HEAPIFY Build the sub-array A[p].. A[q] into a heap: void heapify(int p,int q) { int c = 2 * p; if(c <= q){ if(c+1 <= q && A[c] < A[c+1]) ++c; if(A[p] < A[c]) { swap(c,p); heapify(c,q); }}}
12
Nonrecursive Heapify void heapify(int p, int q) { int c; for( ; c=2*p, c = A[c])break; exchange A[c] and A[p]; } }
13
BUILD HEAP Initially, we build the entire array A[1].. A[n] into a heap. void buildheap(void) { int j; for(j=n/2; j >= 1; --j) heapify(j,n); }
14
HEAPSORT Then we do the “exchange” to put the max element at the end of the array. void heapifyexchange(void) { int j; for(j=n; j >= 2; --j){ heapify(1,j); exchange(1,j); }
15
Final Heapsort Code We put everything together to get heapsort: main() { buildheap(); heapify_exchange(); }
16
Running Time of Heapsort Buildheap() runs in O(n lg(n)) time. heapify_exchange() runs in O(n lg(n)) time. Thus heapsort main() runs in O(n lg(n)) time.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.