Salta al contenuto
Note per Studenti Heap-Sort Report

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 S=S[0] S[1]…S[n−1]S = S[0]\,S[1] \dots S[n-1] be a sequence of nn 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

nn calls to insert (key k→k \to entry (k,null)(k, \text{null})), then nn calls to removeMin (entry (k,null)→(k, \text{null}) \to key kk): the keys come out in increasing order.

Complexity for each implementation of PP

PP Phase A Phase B Resulting sort
Unordered list nn inserts of Θ(1)\Theta(1): Θ(n)\Theta(n) min extraction scans n,n−1,…n, n-1, \dots: Θ(∑i=1ni)=Θ(n2)\Theta\left(\sum_{i=1}^{n} i\right) = \Theta(n^2) Selection sort, Θ(n2)\Theta(n^2)
Ordered list nn insertions of O(n)O(n): Θ(∑i=1ni)=Θ(n2)\Theta\left(\sum_{i=1}^{n} i\right) = \Theta(n^2) nn extractions of Θ(1)\Theta(1): Θ(n)\Theta(n) Insertion sort, Θ(n2)\Theta(n^2)
Heap (array) nn inserts of O(log⁡n)O(\log n) nn removeMin of O(log⁡n)O(\log n) HeapSort, Θ(nlog⁡n)\Theta(n \log n)

With the heap, both phases cost Θ(∑i=1nlog⁡i)=Θ(nlog⁡n)\Theta\left(\sum_{i=1}^{n} \log i\right) = \Theta(n \log n) (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 Θ(nlog⁡n)\Theta(n \log n) to Θ(n)\Theta(n).

Drawback: this version wastes space (insertion into a queue, then re-insertion into the sequence). The in-place version avoids it.

In-place HeapSort

SS is sorted in place using the array itself as a max-heap (key of each internal node ≥\ge keys of its children, i.e. S[i]≥max⁡{S[2i+1],S[2i+2]}S[i] \ge \max\{S[2i+1], S[2i+2]\}), with level numbering: root S[0]S[0], children of S[i]S[i] are S[2i+1],S[2i+2]S[2i+1], S[2i+2], parent S[⌊(i−1)/2⌋]S[\lfloor (i-1)/2 \rfloor], last node S[n−1]S[n-1].

  • Phase A: bottom-up construction, S→S \to 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 k≤lastk \le last of the child of S[i]S[i] with the largest key (2i+12i+1 or 2i+22i+2) if S[i]S[i] is internal, null if it is a leaf.

Phase A: S→S \to max-heap

The parent of the last node S[n−1]S[n-1] is S[⌊(n−2)/2⌋]S[\lfloor (n-2)/2 \rfloor].

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 S[i]S[i] is swapped with its larger child S[k]S[k].)

Invariant (same as the bottom-up construction): at the end of iteration jj the prefix S[0..j−1]S[0..j-1] is unchanged and the suffix S[j..n−1]S[j..n-1] is a forest of max-heaps. Cost Θ(n)\Theta(n) (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 →\to sorted SS

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)
return

Each iteration is equivalent to a removeMax() on the max-heap represented by the prefix of SS.

Invariant. At the end of iteration jj (j=0j = 0 is the beginning of the loop):

  • S[0..n−j−1]S[0..n-j-1] contains the n−jn-j smallest keys arranged as a max-heap;
  • S[n−j..n−1]S[n-j..n-1] contains the jj largest keys sorted in increasing order.

Why it is maintained: at the start (j=0j=0) the whole array is a max-heap and the sorted suffix is empty. At iteration jj the root of the heap S[0..n−j]S[0..n-j] is its maximum, which is ≥\ge every key in the prefix and ≤\le every key of the sorted suffix; the swap puts it in position n−jn-j, extending the sorted suffix. The prefix S[0..n−j−1]S[0..n-j-1] 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 n−1n-1 the prefix has one entry and SS is sorted.

Example (Phase B, n=7n = 7)

At iteration jj the root S[0]S[0] (the current maximum) is swapped with S[n−j]S[n-j]:

jj entry at S[n−j]S[n-j] (moved to the root) maximum moved to S[n−j]S[n-j]
1 S[6]=7S[6] = 7 12
2 S[5]=2S[5] = 2 8
3 S[4]=4S[4] = 4 7
4 S[3]=1S[3] = 1 6
5 S[2]=2S[2] = 2 4
6 S[1]=1S[1] = 1 2

So the sorted suffix grows from the right: 12, then 8, 7, 6, 4, 2, and the last remaining key is 1: S=[1,2,4,6,7,8,12]S = [1, 2, 4, 6, 7, 8, 12].

Complexity

  • Phase A: bottom-up construction, Θ(n)\Theta(n).
  • Phase B: n−1n-1 removeMax() on progressively smaller heaps: Θ(∑i=1n−1log⁡i)=Θ(nlog⁡n)\Theta\left(\sum_{i=1}^{n-1} \log i\right) = \Theta(n \log n).

Total Θ(nlog⁡n)\Theta(n \log n): 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 EE; the priority is the entire object, as if the entries had empty values.
  • By default elements are compared with the natural order of EE.
  • To use it with (key,value)(key, value) pairs: represent the entries with a class implementing Comparable and define compareTo so that the order is based on the key.
java
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