2

So I've read up on heaps, and I understand the basic concept,

but not how to actually implement it.

Basically, my issue is

  1. How you know where to put a new node?

  2. How you know which node to replace the root with when you delete?

svick
  • 236,525
  • 50
  • 385
  • 514
Joe legrae
  • 137
  • 2
  • 4

1 Answers1

0

How do you know where to put a new node?

Typically, although we conceptualize binary heaps as binary trees, we represent them implicitly within an array, with the elements laid out in the order you’d find them in a top-to-bottom, left-to-right scan of the tree. This makes it easy to determine where the new node goes - you place it at the end of the array after all the previous elements.

How you know which node to replace the root with when you delete?

The standard algorithm for replacing the root goes like this:

  1. Swap the last element of the heap with the root of the heap.
  2. Repeatedly swap that element with its smaller child until it is smaller than all its children.
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065