Min-Heap implementation in Java is represented by PriorityQueue which, in turn, is backed by transient Object[] queue;
The quote from its javadoc is
Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2n+1] and queue[2(n+1)].
Why not queue[2n] and queue[2n+1] as Tim Roughgarden states here https://www.coursera.org/learn/algorithms-graphs-data-structures/lecture/KKqlm/heaps-implementation-details-advanced-optional 08:00?
As caco3 mentions in the commments, if the elements in a priority queue are stored in an array, the designers of that priority queue data structure can decide to store the first item in the array at position 0 or position 1.
Putting the first item in position 0 means that children are in positions 2N + 1 and 2N + 2. When the first item is stored in position 1 the children are in positions 2N and 2N + 1.
Either choice can lead to a correct implementation. Starting at 0 saves a little space. But some people feel that the math and code is more elegant when starting at 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.