vim-castle/home/.vim/vimwiki/vimwiki/Heapsort.wiki

72 lines
2.2 KiB
Plaintext

== Heapsort ==
Stats::
:: Worst Case Performance: O(n log n)
:: Best Case Performance: O(n log n)
=== Algorithm ===
The heapsort algorithm can be divided into two parts.
* Step 1: A heap is built out of the data.
* The heap is often placed in an array with the layout of a complete binary tree.
* The complete binary tree maps the binary tree structure into the array indices
* Each array index represents a node.
* The index of the node's parent, left child branch, or right child branch are simple expressions.
* For a zero-based array, the root node is stored at index 0
* If i is the index of the current node, then
* iParent = floor((i-1) / 2)
* iLeftChild = 2*i + 1
* iRightChild = 2*i + 2
* Step 2: A sorted array is created by repeatedly removing the largest element from the heap (the root of the heap), and inserting it into the array. The heap is updated after each removal to maintin the heap. Once all objects have been removed from the heap, the result is a sorted array.
=== Psuedocode ===
{{{
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;
}
}
}
}}}
=== Additional Info ===
Wikipedia Article [http://en.wikipedia.org/wiki/Heapsort]