Heap / Priority Queue — Struktur Data

Heap adalah binary tree khusus di mana parent selalu lebih kecil (min-heap) atau lebih besar (max-heap) dari child-nya. Min-Heap: Parent ≤ Child (root = nilai t

Heap adalah binary tree khusus di mana parent selalu lebih kecil (min-heap) atau lebih besar (max-heap) dari child-nya.

Min-Heap: Parent ≤ Child (root = nilai terkecil) Max-Heap: Parent ≥ Child (root = nilai terbesar)

Operasi dan kompleksitas:

Operasi Kompleksitas
Ambil min/max O(1)
Insert O(log n)
Extract min/max O(log n)
class MinHeap {
  constructor() {
    this.heap = [];
  }

  insert(value) {
    this.heap.push(value);
    this._bubbleUp(this.heap.length - 1);
  }

  extractMin() {
    if (this.heap.length === 0) return undefined;
    const min = this.heap[0];
    const last = this.heap.pop();
    if (this.heap.length > 0) {
      this.heap[0] = last;
      this._sinkDown(0);
    }
    return min;
  }

  _bubbleUp(i) {
    while (i > 0) {
      const parent = Math.floor((i - 1) / 2);
      if (this.heap[parent] <= this.heap[i]) break;
      [this.heap[parent], this.heap[i]] = [this.heap[i], this.heap[parent]];
      i = parent;
    }
  }

  _sinkDown(i) {
    const n = this.heap.length;
    while (true) {
      let smallest = i;
      const left = 2 * i + 1;
      const right = 2 * i + 2;
      if (left < n && this.heap[left] < this.heap[smallest]) smallest = left;
      if (right < n && this.heap[right] < this.heap[smallest]) smallest = right;
      if (smallest === i) break;
      [this.heap[smallest], this.heap[i]] = [this.heap[i], this.heap[smallest]];
      i = smallest;
    }
  }
}

Kegunaan nyata:

🎭 Analogi sehari-hari: Heap = ruang IGD rumah sakit. Bukan urut datang (queue biasa), tapi urut prioritas medis. Yang paling kritis (root) ditangani duluan, gak peduli kapan dia tiba. Setiap pasien baru masuk → diatur sesuai gawatnya. Itu Priority Queue.

💡 Kenapa Heap pakai Array, bukan pointer? Heap adalah complete binary tree — pasti penuh dari kiri. Karena strukturnya predictable, bisa di-encode di array dengan rumus index:

Hasilnya: hemat memori (no pointer) + cache friendly (compact array).

⚠️ Jebakan umum:

🎯 Stack vs Queue vs Priority Queue:

🧪 Tebakan cepat: Cari k elemen terkecil dari 1jt data. Brute sort O(n log n). Pakai max-heap size k → O(n log k) — kalau k kecil, jauh lebih cepat.

TL;DR: Heap = priority queue, parent ≤ children (min) atau ≥ (max). Insert/extract O(log n), peek O(1). Foundation Dijkstra dan banyak algoritma top-k.