forked from embedded2016/unit-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.c
85 lines (66 loc) · 1.26 KB
/
merge.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
#include<stdio.h>
#include<stdlib.h>
typedef struct _List {
struct _List *next;
int value;
} List;
void mergesort(List **headRef);
List* sort(List* a,List* b);
void FrontBackSplit(List* source,List** frontRef, List** backRef);
void mergesort(List** headRef) {
List* head = *headRef;
List* a;
List* b;
if ((head == NULL) || (head->next == NULL))
{
return;
}
FrontBackSplit(head, &a, &b);
mergesort(&a);
mergesort(&b);
*headRef = sort(a, b);
}
List* sort(List* a,List* b) {
List* result = NULL;
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
if (a->value <= b->value)
{
result = a;
result->next = sort(a->next, b);
}
else
{
result = b;
result->next = sort(a, b->next);
}
return(result);
}
void FrontBackSplit(List* source,List** frontRef, List** backRef) {
List* fast;
List* slow;
if (source==NULL || source->next==NULL)
{
*frontRef = source;
*backRef = NULL;
}
else
{
slow = source;
fast = source->next;
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}