Heap-Sort
In questa pagina 3
Sorting through a priority queue
A priority queue (see Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues →) can sort. Let be a sequence of keys.
Algorithm PriorityQueueSort(S)
Phase A: insert the n keys into P one at a time with insert(), encapsulating each key k in an entry (k, null)
Phase B: remove the n entries from P one at a time with removeMin(), and put the key k of each entry (k, null) back into S calls to insert (key entry ), then calls to removeMin (entry key ): the keys come out in increasing order.
Complexity for each implementation of
| Phase A | Phase B | Resulting sort | |
|---|---|---|---|
| Unordered list | inserts of : | min extraction scans : | Selection sort, |
| Ordered list | insertions of : | extractions of : | Insertion sort, |
| Heap (array) | inserts of | removeMin of | HeapSort, |
With the heap, both phases cost (see HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps → for the sum). With the bottom-up construction of HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →, phase A alone drops from to .
Drawback: this version wastes space (insertion into a queue, then re-insertion into the sequence). The in-place version avoids it.
In-place HeapSort
is sorted in place using the array itself as a max-heap (key of each internal node keys of its children, i.e. ), with level numbering: root , children of are , parent , last node .
- Phase A: bottom-up construction, max-heap.
- Phase B: swap the maximum (root) with the last node of the current heap, then down-heap bubbling to restore max-heap order in the heap made of all the elements except the last node. Repeat.
indexMaxChild(S, i, last) returns the index of the child of with the largest key ( or ) if is internal, null if it is a leaf.
Phase A: max-heap
The parent of the last node is .
for j <- floor((n-2)/2) downto 0 do
// down-heap bubbling from S[j]
i <- j
k <- indexMaxChild(S, i, last)
while (k != null AND S[i] < S[k]) do
swap(S[i], S[k])
i <- k
k <- indexMaxChild(S, i, last)
return(In the slides the swap is written swap(S[i], S[j]), a typo: the entry at is swapped with its larger child .)
Invariant (same as the bottom-up construction): at the end of iteration the prefix is unchanged and the suffix is a forest of max-heaps. Cost (see HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →).
Phase B: max-heap sorted
for j <- 1 to n-1 do
swap(S[n-j], S[0])
last <- n - j - 1
// down-heap bubbling from S[0] up to index last
i <- 0
k <- indexMaxChild(S, i, last)
while (k != null AND S[i] < S[k]) do
swap(S[i], S[k])
i <- k
k <- indexMaxChild(S, i, last)
returnEach iteration is equivalent to a removeMax() on the max-heap represented by the prefix of .
Invariant. At the end of iteration ( is the beginning of the loop):
- contains the smallest keys arranged as a max-heap;
- contains the largest keys sorted in increasing order.
Why it is maintained: at the start () the whole array is a max-heap and the sorted suffix is empty. At iteration the root of the heap is its maximum, which is every key in the prefix and every key of the sorted suffix; the swap puts it in position , extending the sorted suffix. The prefix now has the old last entry at the root, so heap order can be violated only at the root, and the down-heap bubbling (bounded by last) restores it. After iteration the prefix has one entry and is sorted.
Example (Phase B, )
At iteration the root (the current maximum) is swapped with :
| entry at (moved to the root) | maximum moved to | |
|---|---|---|
| 1 | 12 | |
| 2 | 8 | |
| 3 | 7 | |
| 4 | 6 | |
| 5 | 4 | |
| 6 | 2 |
So the sorted suffix grows from the right: 12, then 8, 7, 6, 4, 2, and the last remaining key is 1: .
Complexity
- Phase A: bottom-up construction, .
- Phase B:
removeMax()on progressively smaller heaps: .
Total : the same as merge sort, but HeapSort works in place.
Priority queues in Java
java.util.PriorityQueue<E> is a priority queue implemented with a heap.
- It does not store key-value pairs but objects of type ; the priority is the entire object, as if the entries had empty values.
- By default elements are compared with the natural order of .
- To use it with pairs: represent the entries with a class implementing
Comparableand definecompareToso that the order is based on the key.
class MyEntry implements Comparable<MyEntry> {
/* variables and methods that define the entry */
@Override
public int compareTo(MyEntry x) {
/* comparison between the caller and x based on the key */
}
}
PriorityQueue<MyEntry> Q = new PriorityQueue<MyEntry>();Q.poll() returns the entry with the minimum key.
Versione ripasso
- PriorityQueueSort: phase A, inserts of ; phase B,
removeMin()back into . Built on a Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues → implementation:- unordered list: A , B , selection sort;
- ordered list: A , B , insertion sort;
- heap: , HeapSort (phase A becomes with the bottom-up build of HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →).
- Extra space is wasted: use the in-place version.
- In-place HeapSort on a max-heap in the array (children , , parent ):
- A:
for j = floor((n-2)/2) downto 0down-heap from with the larger child (indexMaxChild, swap while ). . - B:
for j = 1 to n-1:swap(S[n-j], S[0]),last = n-j-1, down-heap from the root within . .
- A:
- Invariant B: after iteration , holds the smallest keys as a max-heap, the largest keys sorted increasingly.
- Total , like merge sort, but in place.
- Typical mistakes: using a min-heap in the in-place version (the result would be decreasing); forgetting to bound the down-heap by
lastin phase B; swapping with the first child instead of the larger one; writingswap(S[i], S[j])instead ofswap(S[i], S[k]). - Java:
PriorityQueue<E>is heap-based, natural order of (orcompareToon entries),poll()returns the minimum.