Skip to content

Instantly share code, notes, and snippets.

@magcius
Created March 17, 2012 11:09
Show Gist options
  • Save magcius/2057664 to your computer and use it in GitHub Desktop.
Save magcius/2057664 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
static void
dump_intv (int *intv,
int count)
{
int i;
for (i = 0; i < count; i++) {
printf("%d ", intv[i]);
}
}
static void
mergesort (int *intv,
int *tmp,
int count)
{
if (count == 2) {
if (intv[0] > intv[1]) {
int tmp;
tmp = intv[0];
intv[0] = intv[1];
intv[1] = tmp;
}
} else if (count > 2) {
int alen, blen;
int ia, ib, i;
int *a, *b;
alen = count / 2;
blen = (count + 1) / 2;
memcpy (tmp, intv, sizeof (int) * count);
a = &tmp[0];
b = &tmp[alen];
mergesort (a, &intv[0], alen);
mergesort (b, &intv[alen], blen);
i = 0;
ia = 0;
ib = 0;
while (ia < alen && ib < blen) {
if (a[ia] < b[ib]) {
intv[i] = a[ia];
++ia;
} else {
intv[i] = b[ib];
++ib;
}
++i;
}
if (ia < alen)
memcpy (&intv[i], &a[ia], sizeof (int) * (alen - ia));
if (ib < blen)
memcpy (&intv[i], &b[ib], sizeof (int) * (blen - ib));
}
}
int
main (int argc,
char **argv)
{
int i;
int *numbers, *tmp;
argc --;
argv ++;
numbers = malloc (sizeof (int) * argc);
tmp = malloc (sizeof (int) * argc);
for (i = 0; i < argc; i++) {
numbers[i] = atoi(argv[i]);
}
mergesort (numbers, tmp, argc);
dump_intv (numbers, argc);
printf ("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment