awelgorithms

Reject extract from an empty heap

Updated

If size == 0, refuse. Do not return 0. Do not read a[0]. Underflow is an error path (or a defined empty result, not a fake min).

What to focus on

Guard with isEmpty. After extracting the last item, the next extract is illegal. Nonempty extract is legal.

Worked examples

empty

a = []
  1. size 0
  2. no root

Result: underflow

after last

a = [7], extract then extract again
  1. first yields 7
  2. second sees size 0

Result: second extract underflow

nonempty ok

a = [1, 4, 9], extract
  1. legal

Result: yield 1

Try it

Write extract(a). a is the heap. size is the live count. Occupied slots are a[0..size). If size is 0, refuse. Do not return 0 as a fake min. Print underflow or the yielded value. extract([]) → underflow extract([7]) then extract again → second is underflow extract([1, 4, 9]) → yield 1

The heap may be empty. Do not return 0 as a fake min.