Skip to content

Instantly share code, notes, and snippets.

@obstschale
Created July 23, 2012 13:00
Show Gist options
  • Save obstschale/3163510 to your computer and use it in GitHub Desktop.
Save obstschale/3163510 to your computer and use it in GitHub Desktop.
Merge Sort
void mergeSort(int a[ ], int n)‏
{
int endcstr, endbstr, check, finished = 0; // booleans
int i, j, k, maxc, maxb;
int *b, *c; // pointers for arrays
b = (int *) malloc( n * sizeof(int) );
c = (int *) malloc( n * sizeof(int) );
while ( !finished )‏
{ // distribution pass
i = j = k = 0;
while (i < n)‏
{
b[j++] = a[i++];
while (i < n && a[i-1] <= a[i])
b[j++] = a[i++];
if (i < n)
{
c[k++] = a[i++];
while (i < n && a[i-1] <= a[i])
c[k++] = a[i++];
}
} // end distribution pass
maxb = j; maxc = k; check = 0;
i = j = k = 0; // merge pass
while ( i < n )
{
check++;
endbstr = maxb<=j;
endcstr = maxc<=k;
while (!endbstr || !endcstr)
{
if( !endbstr && (endcstr || b[j] < c[k]))‏
{
a[i++] = b[j++];
endbstr = maxb<=j || b[j]<b[j-1];
}
else
{
a[i++] = c[k++];
endcstr = maxc<=k || c[k]<c[k-1];
}
}
} // end merge pass
finished = check <= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment