7

The most appropriate way to implement a heap is with an array rather than a linked list, why is this?

I don't completely comprehend why this is? is it because it is easier to traverse?

cmehmen
  • 169
  • 1
  • 1
  • 4

2 Answers2

13

It doesn't make any sense at all to implement a heap as a linked list. (The most common kinds of) heaps are inherently binary trees. You can store a heap in an array because it's easy to compute the array index of a node's children: the children of the node at index K live at indices 2K+1 and 2K+2 if indices start at 0 (or at indices 2K and 2K+1 if indices start at 1). It's massively more efficient to find the Kth element of an array than the Kth element of a linked list.

Advantages of storing a heap as an array rather than a pointer-based binary tree include the following.

  • Lower memory usage (no need to store three pointers for every element of the heap).
  • Easier memory management (just one object allocated, rather than N).
  • Better locality of reference (the items in the heap are relatively close together in memory rather than scattered wherever the allocator put them).
John L.
  • 38,985
  • 4
  • 33
  • 90
David Richerby
  • 81,689
  • 26
  • 141
  • 235
  • 1
    Contributors to stackoverflow seem to disagree (not about the linked list part, about using an array vs pointers): http://stackoverflow.com/questions/2027848/heaps-vs-binary-trees-how-to-implement. I'm not sure which is actually better in practice - it'd be interesting to see or run some tests... – Joshua Grochow Jan 08 '16 at 21:12
  • 1
    "Heaps are inherently binary trees": Heaps are technically trees that satisfy the heap property. Such trees don't need to be binary. That said, yes, a (very common) type of heap is a binary heap which are a type of binary tree. – Amelio Vazquez-Reina Feb 24 '20 at 19:48
5

array based implementations are much easier to work with, as they can be iterated through internally making element updates and destruction much simpler. However they only work on heaps with a defined number of children on each node (like binary heaps). If you are doing something like a pairing heap you will need pointers.

Noah Green
  • 51
  • 1
  • 1