Heap Sort
Last updated
Was this helpful?
Last updated
Was this helpful?
Heap sort works by using the heap datastructure. This sorting algorithm has a performance of $O(n*log(n))$ which makes it fast.
Heapsort works by first creating the heap datastructure, so let's say we have an array, it will then convert this array into a heap datastructure which is a tree from top to bottom from left to right with our elements.
After it has done that it will start executing the Heapify algorithm, heapify works by starting on the second last row of our tree and then comparing the 2 childs, if one of the childs is bigger then the parent, then we swap those 2 and we start heapify again from the swapped child.
Once we are done using the recursive Heapify, we get a sorted array!
For the implementation check paragraph §4.4
.
Advantages
$O(1)$ extra space
$O(n*lg(n))$ performance
Disadvantages
Can be hard to implement if you do not understand it completely.
Not stable
Not adaptive
Worst Case
Average Case
Best Case
O(n log n)
O(n log n)
O(n log n)
For the worst case we will act as if we fill the tree. This will give us an execution time of:
Which we can solve by multiplying both terms by a factor 2.
And then we substract both those equations from one another.
Which we can simplify to:
This in turn is a serie which we can shorten down:
Since $2^h \leq n \le 2^{h+1}$ we get that:
which results into a $O(n*lg(n))$ algorithm in the worst case.
Note that the performance is the same for all the trees, we will always have to go down and keep repeating this n log n times no matter what.
The way I started on implementing this algorithm is by drawing it out on a paper step by step, variable by variable.
Once you do that you can see that the trick is to have some sub-methods and finding the correct indexes for this method. By this I found that my methods were:
getChildLeftIndex // $2 * idxEl + 1$, converted into (index << 1) + 1
getChildRightIndex // $2 * (idxEl + 1)$, converted into (index + 1) << 1
getHeightTree // $log_2 (elCount + 1) - 1$, log is heavy so I wrote a shifter till we get this.
getSecondLastHeightStartIndex // Calculate the second last height starting index, this is just $(2^h - 1) - 1$
buildMaxHeap
maxHeapify
100
1.000
10.000
100.000
1.000.000
Random Elements
1.7e-05
0.000303
0.003413
0.041913
0.511796
Ascending Elements
1.7e-05
0.000279
0.003012
0.036692
0.433318
Descending Elements
1.5e-05
0.000268
0.002758
0.035744
0.413004
Heap sort is a fast algorithm that you should use if you know how to implement it.
Credits to for the graphics.