-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.c
78 lines (67 loc) · 1.2 KB
/
mergesort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* merge sort in c99
* creator: kocotian
*
* see LICENSE file for details
*
* go to github.com/kocotian/randomcoding
* for more random codes
*
*/
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRSIZE 8
#define MIN 0
#define MAX 99
void
merge(char *mem, char l, char c, char r)
{
char *umem = malloc(r - l + 1);
char il = l, ir = c + 1, iter = 0;
while(il <= c && ir <= r)
if(mem[il] < mem[ir])
umem[iter++] = mem[il++];
else
umem[iter++] = mem[ir++];
while(il <= c)
umem[iter++] = mem[il++];
while(ir <= r)
umem[iter++] = mem[ir++];
iter = l - 1;
while(++iter < r + 1)
mem[iter] = umem[iter - l];
free(umem);
}
void
msort(char *mem, char l, char r)
{
char c = (l + r) / 2;
if(l >= r) return;
msort(mem, l, c);
msort(mem, c + 1, r);
merge(mem, l, c, r);
}
void
main(void)
{
srand(time(NULL));
char *mem = malloc(ARRSIZE);
char iter = -1;
printf("array before msort: ");
while(++iter < ARRSIZE)
{
mem[iter] = rand() % MAX + MIN;
printf(" %d",
mem[iter]);
}
msort(mem, 0, ARRSIZE - 1);
printf("\narray after msort: ");
iter = -1;
while(++iter < ARRSIZE)
printf(" %d",
mem[iter]);
printf("\n");
free(mem);
}