complexity and applications of heap sort
complexity and applications of heap sort
Time Complexity
Best O(nlog n)
Worst O(nlog n)
Average O(nlog n)
Stability No
Heap Sort has O(nlog n) time complexities for all the cases ( best case,
average case, and worst case).
Let us understand the reason why. The height of a complete binary tree
containing n elements is log n
In the worst case scenario, we will need to move an element from the root
to the leaf node making a multiple of log(n) comparisons and swaps.
During the build_max_heap stage, we do that for n/2 elements so the worst
case complexity of the build_heap step is n/2*log n ~ nlog n .
During the sorting step, we exchange the root element with the last element
and heapify the root element. For each element, this again takes log
n worst time because we might have to bring the element all the way from
the root to the leaf. Since we repeat this n times, the heap_sort step is
also nlog n .
Also since the build_max_heap and heap_sort steps are executed one after
another, the algorithmic complexity is not multiplied and it remains in the
order of nlog n .