krahets/hello-algo · error · IndexError

堆積為空

Error message

堆積為空

What it means

Raised by the pop method of the MyHeap teaching class (a max-heap backed by an array) when is_empty? is true. The guard prevents swapping or popping from an empty backing array, which would produce nil or an out-of-bounds access. It fires before any structural mutation.

Source

Thrown at zh-hant/codes/ruby/chapter_heap/my_heap.rb:83

  ### 從節點 i 開始,從底至頂堆積化 ###
  def sift_up(i)
    loop do
      # 獲取節點 i 的父節點
      p = parent(i)
      # 當“越過根節點”或“節點無須修復”時,結束堆積化
      break if p < 0 || @max_heap[i] <= @max_heap[p]
      # 交換兩節點
      swap(i, p)
      # 迴圈向上堆積化
      i = p
    end
  end

  ### 元素出堆積 ###
  def pop
    # 判空處理
    raise IndexError, "堆積為空" if is_empty?
    # 交換根節點與最右葉節點(交換首元素與尾元素)
    swap(0, size - 1)
    # 刪除節點
    val = @max_heap.pop
    # 從頂至底堆積化
    sift_down(0)
    # 返回堆積頂元素
    val
  end

  ### 從節點 i 開始,從頂至底堆積化 ###
  def sift_down(i)
    loop do
      # 判斷節點 i, l, r 中值最大的節點,記為 ma
      l, r, ma = left(i), right(i), i
      ma = l if l < size && @max_heap[l] > @max_heap[ma]
      ma = r if r < size && @max_heap[r] > @max_heap[ma]

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check heap.is_empty? (or heap.size.zero?) before calling pop.
  2. Use a while !heap.is_empty? loop to drain the heap safely.
  3. Wrap the call in begin/rescue IndexError for defensive draining.
  4. Log or track push/pop counts to detect push/pop imbalance.

Example fix

# before
10.times { max_val = heap.pop }  # crashes when heap has fewer than 10 elements

# after
results = []
results << heap.pop until heap.is_empty?  # drains safely
Defensive patterns

Strategy: validation

Validate before calling

return nil if heap.is_empty?
heap.pop

Type guard

# Ruby: safe pop
def safe_pop(heap)
  heap.is_empty? ? nil : heap.pop
end

Try / catch

begin
  max_val = heap.pop
rescue IndexError
  max_val = nil  # heap was empty
end

Prevention

When it happens

Trigger: Calling heap.pop on a freshly-constructed heap (no elements pushed yet), calling pop more times than elements were pushed, or calling pop in a drain loop without checking emptiness.

Common situations: Draining a heap with a fixed-count loop instead of an emptiness check; popping after a failed or partial push sequence; using heap.pop where peek was intended.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/d0b1f5b5b021f695. Report an issue: GitHub.