-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.c
88 lines (76 loc) · 1.38 KB
/
merge_sort.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
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void merge(int src[], int tmp[], int start, int mid, int end)
{
int i, j, k;
assert(NULL != src);
assert(NULL != tmp);
i = start;
j = mid + 1;
k = start;
while((i<=mid) && (j<=end))
{
if(src[i] <= src[j])
{
tmp[k++] = src[i++];
}
else
{
tmp[k++] = src[j++];
}
}
while(i <= mid)
{
tmp[k++] = src[i++];
}
while(j <= end)
{
tmp[k++] = src[j++];
}
memcpy(src+start, tmp+start, sizeof(int)*(end-start+1));
return;
}
void merge_sort(int src[], int tmp[], int start, int end)
{
int mid;
assert(NULL != src);
assert(NULL != tmp);
mid = (start+end)/2;
if(start < end)
{
merge_sort(src, tmp, start, mid);
merge_sort(src, tmp, mid+1, end);
merge(src, tmp, start, mid, end);
}
else
{
return;
}
}
int main(int argc, char *argv[])
{
int *tmp, *src, index;
assert(argc > 1);
src = malloc(sizeof(int) * (argc-1));
tmp = malloc(sizeof(int) * (argc-1));
if((NULL==tmp) || (NULL == src))
{
return -1;
}
for(index=0; index<argc-1; index++)
{
src[index] = atoi(argv[index+1]);
printf("%d ", src[index]);
}
printf("\n");
merge_sort(src, tmp, 0, argc-2);
printf("the result is:\n");
for(index=0; index<argc-1; index++)
{
printf("%d ", src[index]);
}
printf("\n");
return 0;
}