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

Why is the running time of heapsort $O(n\log n)$?

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

Problem

Heapsort(A)
1 BUILD_MAX_HEAP(A)
2 for i=A.length downto 2
3    exchange A[1] with A[i]
4    A.heapsize=A.heapsize-1
5    MAX_HEAPIFY(A,1)


In the book on algorithms by CLRS the running time of this algorithm is given to be $O(n\lg n)$ as the for loop is executed $n-1$ times and each call of MAX_HEAPIFY takes $O(\lg n)$.

But my question is does MAX_HEAPIFY not depend on height of subtree at which it is called? Why then should it still be the same for all $n-1$ calls as $h$ will obviously differ?

Solution

Each call of MAX_HEAPIFY takes time $O(h) = O(\log n)$, where $h$ is the depth of the heap. Note that big O is an upper bound on the running time, not the exact running time. It is also true that the running time of MAX_HEAPIFY is $O(n)$, for example.

Context

StackExchange Computer Science Q#47315, answer score: 6

Revisions (0)

No revisions yet.