AlgoSteps ランダム記事

Heap sort

ヒープソート

1964年 手順公開

最大の値を配列の右端へ送り、残りの範囲で同じことを繰り返す。

概要

配列の先頭を木の根として、左から順に枝へ値を並べる。どの親も子以上の値を持つように整えると、根に最大値が来る。この形が最大ヒープだ。

根と未確定の右端を入れ替えると、その右端はもう動かさなくてよい。新しい根を大きい方の子と交換しながら下げ、残りを再びヒープにする。図の木にはまだ整列に使う値だけを残す。

動きを見る

技術詳細

時間計算量
最悪 O(n log n)
補助領域
O(1)(反復版)
前提
配列の要素を比較できる
sift_down(root, size):
    while 2 * root + 1 < size
        child = 2 * root + 1
        if child + 1 < size and A[child + 1] > A[child]
            child += 1
        if A[root] >= A[child]
            return
        swap A[root], A[child]
        root = child

n = length(A)
for root = (n // 2) - 1 down to 0
    sift_down(root, n)
for end = n - 1 down to 1
    swap A[0], A[end]
    sift_down(0, end)

最初のヒープは下の段から整えると O(n) で作れる。最大値を末尾に移す交換では、同じ値同士の元の順序が変わることがある。

参考資料