# Running time of heap sort, when all number are identical

Given n numbers that all are identical, then what would be the running time of heap sort?

Will it be in linear time $$O(n)$$ or, best case $$\Theta(n\log n)$$?

It would be $$O(n)$$, because each call to a siftdown or siftup procedure would be executed in $$O(1)$$ if well implemented.

Indeed, in a maxheap, the siftdown procedure is called in the heapify procedure, or to extract a node from the tree, and is defined as follow:

siftdown(x):
while x is not a leaf and x is strictly smaller than its two children:
swap x and its largest child


Since you consider an array of $$n$$ equal values, the test x is strictly smaller than its two children will never be true, so the loop will never be executed and the complexity is $$O(1)$$.

Now, the heapsort procedure in an array of size $$n$$ is defined as follow:

• heapify the array ($$n$$ siftdown from last to first element);
• extract each value ($$n$$ siftdown).

The total complexity is indeed $$O(n)$$. Please note that one can prove that the heapify procedure can be executed in $$O(n)$$ in all cases (and not only with equal values).

• can you please elaborate on this? Apr 2, 2021 at 18:35
• The siftup and siftdown move the current element either up or down in the heap until its in its right place. Since all elements are identical, the right place for any value could be anywhere in the heap, and thus a well-implemented siftup and siftdown would take only O(1) time (on any element it will be run on, it wont change its place), for a total of O(n) Apr 2, 2021 at 18:43
• I have added some details to the explanation. If this is not enough, I recommand that you review the heap data structure and the heapsort in the general case (en.wikipedia.org/wiki/Heapsort). Apr 2, 2021 at 18:53
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 11, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}