Heapsort

Published September 13, 1999 by Yin-So Chen, posted by Myopic Rhino
Do you see issues with this article? Let us know.
Advertisement
By viewing the array as a complete binary tree, Heap Sort transforms such a binary tree into a heap. This algorithm does not require overhead and is not recursive. The algorithm basically follows the following steps:
  1. Sort the complete binary tree (actually an array) so that it becomes a max-heap, thus the first element is always the biggest element.
  2. Since what we want is exactly the opposite (the last element should be the biggest instead), we swap the first element and the last element.
  3. Now we have to re-sort the array (except the last element), so that the first element is again the biggest.
  4. Then we repeat the second step, so that the first element is swapped with the current last element.
  5. We repeat 2, 3 so that all the elements are sorted.
Such a strategy takes the advantage of binary tree. Every time we move an element, we move it to its current position's child. Thus it moves in a greater distance than Insertion Sort.

Below is the pseudo-code of Heap Sort.

Heap Sort(Sorting array A[size])

For each parent node,
{
if there is any child node, we compare it with bigger child. If the parent
is less, we walk down the parent until none of its new children nodes are
greater.
}
While we do not reach the first cell,
{
swap the first cell with the last cell.
Change the last cell index to the cell preceding the last cell.
Walk down the first cell until none of its new children nodes are greater.
}
Cancel Save
0 Likes 0 Comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!

The heapsort is a very dependable in-place sorting algorithm, with a rate of growth of [s]O[/s] (n log n). Though not quite as fast as quicksort, it has no worst-case scenario.

Advertisement
Advertisement