-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmerge_sort.c
More file actions
120 lines (95 loc) · 2.16 KB
/
merge_sort.c
File metadata and controls
120 lines (95 loc) · 2.16 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
int val;
struct node *next;
} node_t;
void add_begin( node_t **head_ref, int val)
{
node_t * new_node;
if( (*head_ref) == NULL)
{
(*head_ref) = malloc(sizeof(node_t));
(*head_ref)->val = val;
(*head_ref)->next = NULL;
return;
}
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void print_list( node_t *head)
{
node_t *current = head;
while(current != NULL)
{
printf("%d, ", current->val);
current = current->next;
}
}
void FrontBackSplit(node_t* source, node_t** frontRef, node_t** backRef)
{
node_t* fast;
node_t* slow;
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;
}
node_t* SortedMerge(node_t* a, node_t* b)
{
node_t* result = NULL;
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
if (a->val >= b->val) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return (result);
}
void merge_sort( node_t** head_ref)
{
node_t *temp = (*head_ref);
node_t* a;
node_t* b;
if( temp == NULL || temp->next == NULL )
return;
FrontBackSplit(temp, &a, &b);
merge_sort(&a);
merge_sort(&b);
*head_ref = SortedMerge(a, b);
}
int main()
{
node_t *head = NULL;
node_t *temp = NULL;
srand( time(NULL) );
for(int i = 0; i < 15; i++)
{
add_begin( &head, rand() % 50 );
}
print_list( head );
puts("");
get_length( head );
merge_sort(&head);
;
printf("Sorted List: ");
print_list( head );
return 0;
}