Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created April 15, 2011 01:13
Show Gist options
  • Save radiofreejohn/920937 to your computer and use it in GitHub Desktop.
Save radiofreejohn/920937 to your computer and use it in GitHub Desktop.
Simple mergesort from Sedgewick's Algorithms in C++
#include <stdio.h>
#include "numbers.h" // https://gist.github.com/911872
int main()
{
struct numbers a;
struct numbers b;
/*
I feel like a tool, sort of. I spent more time than I should admit using
generateRandoms here, forgetting that mergesort can only merge two arrays
that have already been sorted.
*/
a = generateRange(1,50);
b = generateRange(-201,250);
int maxVal = 999;
a.values[a.size-1] = maxVal;
b.values[b.size-1] = maxVal;
int c[a.size+b.size-2];
int i = 0, j = 0, k;
for (k = 0; k < a.size+b.size-2; k++)
c[k] = (a.values[i] < b.values[j]) ? a.values[i++] : b.values[j++];
for (k = 0; k < a.size+b.size-2; k++)
printf(" %d", c[k]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment