vim-castle/.vim/vimwiki/vimwiki_html/Merge Sort.html

76 lines
2.1 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>Merge Sort</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2 id="toc_0.1">Merge Sort</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>
<ul>
<li>
Conceptually, a merge sort works as follows:
<ol>
<li>
Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
<li>
Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
</ol>
</ul>
<h3 id="toc_0.1.2">Psuedocode</h3>
<pre>
/* Array A[] has the items to sort; array B[] is a work array */
function BottomUpSort(int n, int A[], int B[]) {
int width;
/* Each 1-element run in A is already "sorted". */
/* Make successively longer sorted runs of length 2, 4, 8, 16... until whole array is sorted. */
for(width = 1; width &lt; n; width = 2 * width) {
int i;
/* Array A is full of runs of length width. */
for(i = 0; i &lt; n; i = i + 2 * width) {
/* Merge two runs: A[i:i+width-1] and A[i+width:i+2*width-1] to B[] */
/* or copy A[i:n-1] to B[] ( if(i+width &gt;= n) ) */
BottomUpMerge(A, i, min(i+width, n), min(i+2*width, n), B);
}
}
}
BottomUpMerge(int A[], int iLeft, int iRight, int iEnd, int B[]) {
int i0 = iLeft;
int i1 = iRight;
int j;
/* While there are elements in the left or right lists */
for(j = iLeft; j &lt; iEnd; j++) {
/* If left list head exists and is &lt;= existing right list head */
if(i0 &lt; iRight &amp;&amp; (i1 &gt;= iEnd || A[i0] &lt;= A[i1])) {
B[j] = A[i0];
i0 = i0 + 1;
} else {
B[j] = A[i1];
i1 = i1 + 1;
}
}
}
</pre>
<h3 id="toc_0.1.3">Additional Info</h3>
<p>
Wikipedia Article [<a href="http://en.wikipedia.org/wiki/Merge_Sort]">http://en.wikipedia.org/wiki/Merge_Sort]</a>
</p>
</body>
</html>