Heap Sort Time Complexity

Heap Sort Time Complexity

Consider the below figure and suppose that The heapsort technique is performed to an n-element array A. The method is divided into two phases for better understanding, and the complexity of each phase is evaluated independently.


Fig. 01: Data array 'A' of n-length.

First Phase: Now consider that 'H' is a heap for finding the complexity of heapsort. Take note that the number of comparisons required to locate the suitable location of a new member ITEM in 'H' cannot exceed the depth of the 'H' heap.

The heap H's depth is totally restricted by log2m, where m is the number of items in the heap 'H'.

As a result, the total number of first_phase(n) comparisons required to insert the n items of the data array A into 'H' is constrained as follows:

first_phase(n) = n log2 n

So, at the last, the first phase time complexity is proportional to n log2 n.

Second Phase: Assume that the heap 'H' is totally free with m elements, that the left and right subtrees of 'H' are heaps, and that 'L' is the root of 'H'. Re-heaping employs four comparisons to shift the node 'L' one step down the tree 'H'.


Fig. 02: The heap 'H' with 'L' root and Child.

Because the depth of H can not exceed log2 m, re-heaping employs no more than four log2, m comparisons to locate the right location of L in the tree H. Are you thinking, what is the 'm'? Don't worry. The m represents the number of items in the heap 'H'.

This indicates that the total number second_phase(n) of comparisons required to delete the n elements of A from the heap 'H', requiring re-heaping n times, is constrained as follows:

second_phase(n) = 4n log2 n

Ok. Finally, we get the second phase of time complexity. We can say that the time complexity of the second phase for the heap sort is proportional to n log2 n.


Fig. 03: First phase and Second phase.

Finally, the time complexity of heap sort is,

Time Complexity = First Phase Time Complexity = Second Phase Time Complexity

Time Complexity = first_phase(n) = second_phase(n)

Time Complexity =  n log2 n = n log2 n

The time complexity of heapsort with notation is O(log2 n).

Read Similar Post

1. Merge Sort Time Complexity

2. Quick Sort Time Complexity

3. Insertion Sort Time Complexity

4. Runtime Reduction of a Linear Search

5. Selection Sort Time Complexity

6. Bubble Sort Time Complexity

Post a Comment

Previous Post Next Post