Lecture 10 - Computer Science at CCSU

Download Report

Transcript Lecture 10 - Computer Science at CCSU

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.
Step2: Do m removeItem operations, putting the elements removed from
the heap into the place just vacated by the shrinking heap.
Advantages of heap sort:
1 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.
2 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
8
1
14
3
10
10
1
15
3
...
13
8 15
10
1
14
8
7 4
6
2 3
11
5
9
Constructing a heap (contd.)
2. Bottom-up, i.e. arrange the unsorted list in a binary tree
3
1
8
14
13
10
7
4
15
2
6
9
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
1
10
7
4
8
2
6
9
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
1
5
2
4
8
11 13
6
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)
y := y - 1
}
y := n
while (y > 1) {
temp := A[1], A[1] := A[y],
A[y] := temp, y := y - 1
downheap(A[y], 1, precedes)
}
O(n/2 log n)
O(n log n)
Overall efficiency: O(1.5 n log n)