二分ヒープとヒープソート
最大/最小ヒープの配列と木のデュアルビュー、Siftアニメーション。
このツールについて
二分ヒープは、ただの配列に格納した完全二分木です。インデックス i の子は 2i+1 と 2i+2、親は ⌊(i−1)/2⌋ にあります。最大ヒープではどの親も子以上の値を持ち(最小ヒープはその逆)、先頭の要素は常に最大値(または最小値)です。優先度付きキューを実装する標準的な方法です。
このラボは木と配列を並べて描き、挿入時の sift-up、取り出し時の sift-down、O(n) のボトムアップによるヒープ構築、そしてヒープソートをアニメーションで見せます。最大ヒープと最小ヒープを切り替えると、同じ操作を順序を逆にして確認できます。
使い方 二分ヒープとヒープソート
- 最大ヒープか最小ヒープを選びます。切り替えると、現在の値から新しい種類の正しいヒープを作り直します。
- 値を挿入すると、配列の末尾に置かれ、親に勝っている間は上へ入れ替わっていきます。
- 先頭を取り出すと、最後の要素が根に移り、大きい(または小さい)ほうの子と入れ替わりながら沈んでいきます。
- 「ヒープ構築」や「ヒープソート」を実行すると、配列のインデックスをハイライトしながらアルゴリズム全体をステップごとに見られます。
使用例
最大ヒープへの挿入
[50, 30, 40, 10, 20] に 45 を挿入
45 はインデックス 5 に追加され、親の 40 と入れ替わる → [50, 30, 45, 10, 20, 40]
最大値の取り出し
[50, 30, 45, 10, 20, 40]
50 を返す。40 が根に移って沈む → [45, 30, 40, 10, 20]
ヒープソート
[4, 10, 3, 5, 1]
[1, 3, 4, 5, 10] — 最大ヒープを作り、根を末尾と入れ替える操作を繰り返す
5 つの言語による実装
同じアルゴリズムを Python、JavaScript、Java、Go、C++ で実装しています。どのプログラムもそのまま実行でき、出力結果をコメントに記しています。
class MinHeap:
def __init__(self):
self.a = []
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0: # sift up
parent = (i - 1) // 2
if a[parent] <= a[i]:
break
a[parent], a[i] = a[i], a[parent]
i = parent
def pop(self):
a = self.a
top = a[0]
last = a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while True: # sift down
left, right, smallest = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
break
a[i], a[smallest] = a[smallest], a[i]
i = smallest
return top
def __len__(self):
return len(self.a)
h = MinHeap()
for x in [5, 3, 8, 1, 9, 2]:
h.push(x)
print(h.a) # [1, 3, 2, 5, 9, 8]
print([h.pop() for _ in range(len(h))]) # [1, 2, 3, 5, 8, 9] class MinHeap {
constructor() {
this.a = [];
}
get size() {
return this.a.length;
}
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up
const parent = (i - 1) >> 1;
if (a[parent] <= a[i]) break;
[a[parent], a[i]] = [a[i], a[parent]];
i = parent;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
const n = a.length;
for (;;) { // sift down
const left = 2 * i + 1, right = 2 * i + 2;
let smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest === i) break;
[a[i], a[smallest]] = [a[smallest], a[i]];
i = smallest;
}
}
return top;
}
}
const h = new MinHeap();
for (const x of [5, 3, 8, 1, 9, 2]) h.push(x);
console.log(h.a.join(', ')); // 1, 3, 2, 5, 9, 8
const sorted = [];
while (h.size > 0) sorted.push(h.pop());
console.log(sorted.join(', ')); // 1, 2, 3, 5, 8, 9 import java.util.ArrayList;
import java.util.List;
public class Main {
static class MinHeap {
final List<Integer> a = new ArrayList<>();
int size() { return a.size(); }
void push(int x) {
a.add(x);
int i = a.size() - 1;
while (i > 0) { // sift up
int parent = (i - 1) / 2;
if (a.get(parent) <= a.get(i)) break;
swap(parent, i);
i = parent;
}
}
int pop() {
int top = a.get(0);
int last = a.remove(a.size() - 1);
if (!a.isEmpty()) {
a.set(0, last);
int i = 0, n = a.size();
while (true) { // sift down
int left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a.get(left) < a.get(smallest)) smallest = left;
if (right < n && a.get(right) < a.get(smallest)) smallest = right;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
}
return top;
}
private void swap(int i, int j) {
int t = a.get(i);
a.set(i, a.get(j));
a.set(j, t);
}
}
public static void main(String[] args) {
MinHeap h = new MinHeap();
for (int x : new int[] {5, 3, 8, 1, 9, 2}) h.push(x);
System.out.println(h.a); // [1, 3, 2, 5, 9, 8]
List<Integer> sorted = new ArrayList<>();
while (h.size() > 0) sorted.add(h.pop());
System.out.println(sorted); // [1, 2, 3, 5, 8, 9]
}
} package main
import "fmt"
type MinHeap struct{ a []int }
func (h *MinHeap) Len() int { return len(h.a) }
func (h *MinHeap) Push(x int) {
h.a = append(h.a, x)
i := len(h.a) - 1
for i > 0 { // sift up
parent := (i - 1) / 2
if h.a[parent] <= h.a[i] {
break
}
h.a[parent], h.a[i] = h.a[i], h.a[parent]
i = parent
}
}
func (h *MinHeap) Pop() int {
a := h.a
top := a[0]
n := len(a) - 1
a[0] = a[n]
a = a[:n]
i := 0
for { // sift down
left, right, smallest := 2*i+1, 2*i+2, i
if left < n && a[left] < a[smallest] {
smallest = left
}
if right < n && a[right] < a[smallest] {
smallest = right
}
if smallest == i {
break
}
a[i], a[smallest] = a[smallest], a[i]
i = smallest
}
h.a = a
return top
}
func main() {
h := &MinHeap{}
for _, x := range []int{5, 3, 8, 1, 9, 2} {
h.Push(x)
}
fmt.Println(h.a) // [1 3 2 5 9 8]
var sorted []int
for h.Len() > 0 {
sorted = append(sorted, h.Pop())
}
fmt.Println(sorted) // [1 2 3 5 8 9]
} #include <iostream>
#include <utility>
#include <vector>
class MinHeap {
public:
std::vector<int> a;
bool empty() const { return a.empty(); }
void push(int x) {
a.push_back(x);
size_t i = a.size() - 1;
while (i > 0) { // sift up
size_t parent = (i - 1) / 2;
if (a[parent] <= a[i]) break;
std::swap(a[parent], a[i]);
i = parent;
}
}
int pop() {
int top = a[0];
a[0] = a.back();
a.pop_back();
size_t i = 0, n = a.size();
while (true) { // sift down
size_t left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest == i) break;
std::swap(a[i], a[smallest]);
i = smallest;
}
return top;
}
};
int main() {
MinHeap h;
for (int x : {5, 3, 8, 1, 9, 2}) h.push(x);
for (int x : h.a) std::cout << x << ' '; // 1 3 2 5 9 8
std::cout << '\n';
while (!h.empty()) std::cout << h.pop() << ' '; // 1 2 3 5 8 9
std::cout << '\n';
} LeetCode で練習
このアルゴリズムを使う定番の問題です。ラボで動きを確かめたら挑戦してみましょう。リンク先は LeetCode(英語)です。
コスト
- 先頭の参照:O(1)。挿入と取り出し:O(log n)、根から葉への経路 1 本分。
- ボトムアップのヒープ構築:O(n)。ほとんどのノードは下のほうにあり、少ししか沈まないからです。
- ヒープソート:どんな場合も O(n log n)、追加メモリ不要ですが安定ではありません。
ヒープが使われる場面
スケジューラーやイベントシミュレーションは優先度で次のジョブを選びます。ダイクストラ法やプリム法は最も近い頂点を取り出し、top-k の問い合わせはサイズ k のヒープを保ち、k 個のソート済みファイルのマージには各ファイルの先頭を入れたヒープを使います。多くの言語に標準で用意されています:Python の heapq、Java の PriorityQueue、C++ の std::priority_queue。
よくある質問
ツールの仕様やセキュリティに関する疑問にお答えします。
ノードとポインタではなく配列を使うのはなぜですか?
ヒープは常に完全木なので隙間がありません。ポインタの代わりにインデックスの計算で済み、メモリを節約でき、キャッシュ効率も良くなります。
ヒープで値を素早く探せますか?
いいえ。任意の値を探すには O(n) かかります。順序に基づく検索が必要なら、平衡探索木を使いましょう。
ヒープ構築が O(n log n) ではなく O(n) なのはなぜですか?
sift-down のコストはノードの下の高さで決まります。半分のノードは葉(コスト 0)、4 分の 1 は高さ 1、という具合で、合計は約 2n に収束します。
入力したデータやファイルは安全ですか?
完全に安全です。本ツールは100%ブラウザ内部で動作し、データがサーバーに送信されることは一切ありません。
関連ツール
注目のプロダクト tech-fun.net
便利なAI・生産性ツールとゲーム
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.