Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is element zero of a heap array not used?

Tags:

java

heap

Here's my rough sketch of the beginning of a heap with arbitrary values

 0   1    2    3    4    5    6    7    8    9   ...
[-] [10] [14] [15] [22] [21] [24] [23] [44] [30] ...

Why must the element in array[0] always be set to null?
Or why is it that we are not supposed to use it?

like image 810
Ernest Avatar asked Feb 27 '12 08:02

Ernest


People also ask

At what index does heap start at?

BinaryHeap and it starts the heap implementation from index 1.

Why heap is not ordered?

However, a heap is not a sorted structure; it can be regarded as being partially ordered. A heap is a useful data structure when it is necessary to repeatedly remove the object with the highest (or lowest) priority, or when insertions need to be interspersed with removals of the root node.

Which node has the minimum key in the heap?

A Min Heap Binary Tree is a Binary Tree where the root node has the minimum key in the tree.

What is the big O of adding an element to a heap?

For a random heap, and for repeated insertions, the insertion operation has an average-case complexity of O(1).


1 Answers

There are several ways to represent a binary heap as an array.

There is a way whereby element zero is used; there is also a way whereby element zero is not used:

  1. root is element 0; children of element n are elements 2n+1 and 2n+2;
  2. root is element 1; children of element n are elements 2n and 2n+1.

Neither is more "correct" than the other. The former is a better fit for programming languages that use zero-based arrays, whereas the latter is a better fit for languages with one-based arrays.

It would appear that you've encountered an implementation that uses the second approach. Since the language in question, Java, uses zero-based arrays, element zero exists but is not being used.

like image 109
NPE Avatar answered Sep 16 '22 18:09

NPE