HEAPS
We can implement priority queues using d-heaps, which are d-ary trees.
Here we will concentrate on 2-heaps, that is, heaps which are implemented
using binary trees. A heap is a partially ordered tree with all levels full
execpt possibly the last. In the bottom level items must be in the
leftmost nodes. The height of 2-heap with n nodes
is . The nodes of a d-heap can be stored in
an array in breadth-first order. For any node with array index i its
parent is at position
, and for any node i
its children will have indices in the range [d(i-1)+2 .. di+1].
For a 2-heap these values are
and
[2i .. 2i+1].
item findmin() ifreturn null |
return h[1] fi end findmin void insert(item e) n := n + 1; h[n] := e siftup(n) end insert heap makeheap(array s)
; n := 0 for
n := n+1; h[n] := e rof
do
siftdown(j);
od end makeheap item delmin() if
return null fi e := h[1] h[1] := h[n - -] siftdown(1) return e end delmin
void siftup(int i) e := h[i]do
and h[p].key >
h[i] := h[p]; i := p
od h[i] := e end siftup void siftdown(int i) e := h[i] g := minchild(i) do
and h[g].key < e.key
h[i] := h[g]; i := g g := minchild(i) od h[i] := e end siftdown int minchild(int i) if
return 0
![]()
return min_index{h[2i].key, h[2i + 1].key} fi end minchild