-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort2.c
61 lines (54 loc) · 1.05 KB
/
sort2.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
#include <stdio.h>
#define LEN 8
int a[LEN] = {5, 2, 4, 7, 1, 3, 2, 6};
void merge(int start, int mid, int end)
{
int n1 = mid - start + 1;
int n2 = end - mid;
int left[n1], right[n2];
int i, j, k;
for (i = 0; i < n1; i++){
left[i] = a[start+i];
}
for (j = 0; j < n2; j++){
right[j] = a[mid+1+j];
}
i = j = 0;
k = start;
while (i < n1 && j < n2){
if (left[i] < right[j]){
a[k++] = left[i++];
}else{
a[k++] = right[j++];
}
}
while (i < n1){
a[k++] = left[i++];
}
while (j < n2){
a[k++] = right[j++];
}
}
void sort(int start, int end)
{
int mid;
if (start < end){
mid = (start + end) / 2;
printf("sort (%d-%d, %d-%d) %d %d %d "
"%d %d %d %d %d\n", start, mid, mid+1, end,
a[0], a[1], a[2], a[3], a[4], a[5],
a[6], a[7]);
sort(start, mid);
sort(mid+1, end);
merge(start, mid, end);
printf("merge (%d-%d, %d-%d) to %d %d %d "
"%d %d %d %d %d\n", start, mid, mid+1, end,
a[0], a[1], a[2], a[3], a[4], a[5],
a[6], a[7]);
}
}
int main(int argc, char const *argv[])
{
sort(0, LEN-1);
return 0;
}