-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.cpp
103 lines (88 loc) · 1.34 KB
/
merge_sort.cpp
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
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
node* head = NULL;
node* tail = NULL;
void insert(int x){
node *temp = new node(x);
if(head == NULL)
{
head = temp;
tail = temp;
}
tail->next = temp;
tail = temp;
}
void display(node *head)
{
node* temp = head;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
node *sortedMerge(node *a, node *b)
{
if(a == NULL) return b;
if(b == NULL) return a;
node *res = NULL;
if(a->data <= b->data)
{
res = a;
res->next = sortedMerge(a->next, b);
}
else
{
res = b;
res->next = sortedMerge(a, b->next);
}
return res;
}
void merge_sort(node **head_ref)
{
node *head = *head_ref;
if(head == NULL || head->next == NULL) return;
node *slow = *head_ref;
node *fast = (*head_ref)->next;
while(fast != NULL)
{
fast = fast->next;
if(fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
node *left = *head_ref;
node *right = slow->next;
slow->next = NULL;
merge_sort(&left);
merge_sort(&right);
*head_ref = sortedMerge(left, right);
}
int main()
{
int n,x;
cout << "Enter n: ";
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> x;
insert(x);
}
merge_sort(&head);
cout << "sorted linked list: ";
display(head);
return 0;
}