Created
March 17, 2012 09:52
-
-
Save magcius/2057203 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
swap (int *a, | |
int *b) | |
{ | |
int tmp = *a; | |
*a = *b; | |
*b = tmp; | |
} | |
static void | |
mergesort (int *intv, | |
int count) | |
{ | |
if (count == 2) { | |
if (intv[0] > intv[1]) | |
swap (&intv[0], &intv[1]); | |
} else if (count > 2) { | |
int halfcount, ibm; | |
int ia, ib; | |
int *a, *b; | |
int *tmp; | |
halfcount = count / 2; | |
tmp = malloc (sizeof (int) * count); | |
memcpy (tmp, intv, sizeof (int) * count); | |
a = &tmp[0]; | |
b = &tmp[halfcount]; | |
ibm = halfcount; | |
if (count % 2) | |
++ibm; | |
mergesort (a, halfcount); | |
mergesort (b, ibm); | |
ia = ib = 0; | |
while (ia < halfcount && ib < ibm) { | |
if (*a < *b) | |
intv[(ia++)+ib] = *a++; | |
else | |
intv[ia+(ib++)] = *b++; | |
} | |
while (ia < halfcount) | |
intv[(ia++)+ib] = *a++; | |
while (ib < ibm) | |
intv[ia+(ib++)] = *b++; | |
free (tmp); | |
} | |
} | |
int | |
main (int argc, | |
char **argv) | |
{ | |
int i; | |
int *numbers; | |
argc --; | |
argv ++; | |
numbers = malloc (sizeof (int) * argc); | |
for (i = 0; i < argc; i++) { | |
numbers[i] = atoi(argv[i]); | |
} | |
mergesort (numbers, 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