The heapsort algorithm can be divided into two parts.
function heapsort(a, count) { // Build the heap in array a so that largest value is at the root heapify(a, count) // The following loop maintains the invariants that a[0:end] is a heap and every element // beyond end is greater than everything before it (so a[end:count] is in sorted order)) end = count - 1; while(end > 0) { // a[0] is the root and largest value. The swap moves it in front of the sorted elements. swap(a[end], a[0]) // The heap size is reduced by one end = end - 1; // The swap ruined the heap property, so restore it siftDown(a, 0, end); } } function heapify(a, count) { start = floor((count - 2) / 2); while(start >= 0) { siftDown(a, start, count-1); start = start - 1; } } function siftDown(a, start, end) { root = start; while((root * 2 + 1) <= end) { child = (root * 2 + 1); swap = root; if(a[swap] < a[child]) { swap = child; } if((child+1) <= end and a[swap] < a[child+1]) { swap = child + 1; } if(swap != root) { swap(a[root], a[swap]); root = swap; } else { return; } } }
Wikipedia Article [http://en.wikipedia.org/wiki/Heapsort]