60 likes | 476 Views
Heap Sort. The idea : build a heap containing the elements to be sorted, then remove them in order. Let n be the size of the heap, and m be the number of elements to be sorted. The following two steps implement heap sort: Step1 : Construct the heap by doing m insertItem operations.
E N D
Heap Sort The idea: build a heap containing the elements to be sorted, then remove them in order. Let n be the size of the heap, and m be the number of elements to be sorted. The following two steps implement heap sort: Step1: Construct the heap by doing minsertItem operations. Step2: Do mremoveItem operations, putting the elements removed from the heap into the place just vacated by the shrinking heap. Advantages of heap sort: • All heap methods, including removeItem and insertItem are O(log n) methods, i.e. each of the two steps takes O(n log n) time. Ignoring the constant of proportionality, runtime efficiency of heap sort is O(n log n) -- much better compared to the quadratic runtime for elementary sorting methods. • Heap sort is in-place sorting method, i.e. uses no extra memory
Constructing a heap Consider the following list of integers which must be sorted: 3 1 8 14 10 15 9 13 7 4 2 6 5 11 There are two ways to construct the heap: 1. Top-down, i.e. starting with the empty heap insert one element at a time, fix the heap condition and insert the next element. 3 3 3 8 1 1 8 1 3 14 14 14 15 8 3 10 3 ... 13 14 1 10 1 8 15 10 8 6 11 1 7 4 2 3 5 9
Constructing a heap (contd.) 2. Bottom-up, i.e. arrange the unsorted list in a binary tree 3 1 8 14 10 15 9 13 7 4 2 6 5 11 Each subtree, starting from the rightmost subtree at the lowest level, is viewed as a heap and the heap condition is fixed. When the left end of the current level is reached, move up to the next level and process it again from right to left until the root is processed. The resulting heap in this example is the following: 15 14 11 13 10 8 9 1 7 4 2 6 5 3
The sorting step When the heap is constructed, start removing the largest element (or the smallest, depending on the ordering relationship) until only one item is left on the heap, and put the item removed into the place vacated by the shrinking heap. After the first four steps, we have 10 7 9 3 5 8 6 1 2 4 11 13 14 15
The heapSort method (assuming bottom-up construction) Algorithm heapSort (A[n], precedes) Input: array A[n] representing the heap, precedes, a comparator object defining the ordering relationship Output: array A[n] represented a sorted (according to the precedes function) list. int y := n / 2 while (y > 0) { downheap (A[n], y, precedes) O(n/2 log n) y := y - 1 } y := n while (y > 1) { temp := A[1], A[1] := A[y], A[y] := temp, y := y - 1 O(n log n) downheap(A[y], 1, precedes) } Overall efficiency: O(1.5 n log n)