vim-castle/.vim/vimwiki/vimwiki_html/Heapsort.html

119 lines
2.7 KiB
HTML
Raw Normal View History

2015-01-14 23:41:47 +00:00
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="Stylesheet" type="text/css" href="style.css">
<title>Heapsort</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2 id="toc_0.1">Heapsort</h2>
<dl>
<dt>Stats</dt>
<dd>Worst Case Performance: O(n log n)</dd>
<dd>Best Case Performance: O(n log n)</dd>
</dl>
<h3 id="toc_0.1.1">Algorithm</h3>
<p>
The heapsort algorithm can be divided into two parts.
</p>
<ul>
<li>
Step 1: A heap is built out of the data.
<ul>
<li>
The heap is often placed in an array with the layout of a complete binary tree.
<li>
The complete binary tree maps the binary tree structure into the array indices
<ul>
<li>
Each array index represents a node.
<li>
The index of the node's parent, left child branch, or right child branch are simple expressions.
<li>
For a zero-based array, the root node is stored at index 0
<li>
If i is the index of the current node, then
<ul>
<li>
iParent = floor((i-1) / 2)
<li>
iLeftChild = 2*i + 1
<li>
iRightChild = 2*i + 2
</ul>
</ul>
</ul>
<li>
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.
</ul>
<h3 id="toc_0.1.2">Psuedocode</h3>
<pre>
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 &gt; 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 &gt;= 0) {
siftDown(a, start, count-1);
start = start - 1;
}
}
function siftDown(a, start, end) {
root = start;
while((root * 2 + 1) &lt;= end) {
child = (root * 2 + 1);
swap = root;
if(a[swap] &lt; a[child]) {
swap = child;
}
if((child+1) &lt;= end and a[swap] &lt; a[child+1]) {
swap = child + 1;
}
if(swap != root) {
swap(a[root], a[swap]);
root = swap;
} else {
return;
}
}
}
</pre>
<h3 id="toc_0.1.3">Additional Info</h3>
<p>
Wikipedia Article [<a href="http://en.wikipedia.org/wiki/Heapsort]">http://en.wikipedia.org/wiki/Heapsort]</a>
</p>
</body>
</html>