HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Build-Max-Heap: Why Start i at floor(A.length/2) rather than A.length?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
whylengththanheaprathermaxstartbuildfloor

Problem

Taken from CLRS third edition, a procedure is given for Build-Max-Heap

function a = build_MaxHeap(a)
for i = floor(length(a)/2): -1 : 1        // i = n downto 1
     a = max_heapify(a,i);
end


My question is why use floor(length(a)/2)? How is it different than using length(a)? Is this the same thing?

function a = build_MaxHeap(a)
for i = length(a): -1 : 1        // i = n downto 1
     a = max_heapify(a,i);
end

Solution

It isn't, neither from a complexity nor from a correctness point of view, however, by starting the counter at $n$ you are doing useless work.

Heapify is a procedure that, if invoked on a node $v$ such that the trees rooted in its children are binary heaps, turns the tree rooted in $v$ into a binary heap. Trees that contain only one node are trivially binary heaps, therefore, you may just start running the algorithm from the first non-leaf node: invoking heapify on the leaves wouldn't have done anything, anyway.

Context

StackExchange Computer Science Q#71786, answer score: 3

Revisions (0)

No revisions yet.