I read everywhere that the time complexity of heapsort is O(nlog(n))
in the worst case. But we also read everywhere that it is a common misconception that a heap is built in O(nlog(n))
. Instead, you can make a heap in O(n)
. So considering that a heap can be made in O(n)
, look at the following sorting algorithm and tell me where I am wrong in analyzing its time complexity.
- Put
n
elements into a heap (time:O(n)
) - Until the heap is empty, pop each element and copy it into an array. (time:
O(n)
. Why? because in the same way all elements can be put into a heap inO(n)
, all of them can also be extracted inO(n)
. Right?).
All in all, the complexity is O(n)+O(n)
which is O(n)
. But here, we also need an additional memory of O(n)
.
I know the traditional heapsort has time complexity of O(nlog(n))
and memory complexity of O(1)
. But isn't this heapsort too? And it provides O(n)
even in the worst case, unlike the traditional heapsort algorithm.