-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15_MergeSort.c
92 lines (76 loc) · 1.5 KB
/
15_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
79
80
81
82
83
84
85
86
87
88
89
#include "linked_list.h"
void FrontBackSplit (struct node *source, struct node **frontRef,struct node **backRef)
{
struct node *findlen = source;
int len = Length(source);
int i;
if (len < 2){
*frontRef = source;
*backRef = NULL;
}
else {
int mid = (len-1)/2;
for (i = 0; i < mid;i++) {
findlen = findlen->next;
}
*frontRef = source;
*backRef = findlen->next;
findlen->next = NULL;
}
}
void MoveNode(struct node **destRef, struct node **sourceRef)
{
struct node *a = *destRef;
struct node *b = *sourceRef;
*sourceRef = b->next;
b->next = *destRef;
*destRef = b;
}
struct node *SortedMerge (struct node *a, struct node *b)
{
struct node *aa = a;
struct node *bb = b;
struct node *result = NULL;
struct node **ref = &result;
while (1) {
if (aa == 0) {
*ref = bb;
break;
}
else if (bb == 0) {
*ref = aa;
break;
}
else if (aa->data <= bb->data) {
MoveNode(ref,&aa);
}
else {
MoveNode(ref,&bb);
}
ref = &((*ref)->next);
}
return result;
}
void MergeSort (struct node **headRef)
{
struct node *temp = *headRef;
struct node *a = NULL;
struct node *b = NULL;
if (Length(*headRef) < 2)
return;
FrontBackSplit (temp, &a, &b);
MergeSort(&a);
MergeSort(&b);
*headRef = SortedMerge(a,b);
}
main()
{
struct node *p = BuildOneTwoThree();
MergeSort(&p);
struct node *s = p;
while (p != 0) {
printf("%d ",p->data);
p = p->next;
}
return 0;
}