-
Notifications
You must be signed in to change notification settings - Fork 0
/
LLmergesort.cpp
153 lines (129 loc) · 1.68 KB
/
LLmergesort.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int d)
{
data=d;
next=NULL;
}
};
void insertathead(node*&head,int data)
{
node*n=new node(data);
n->next=head;
head=n;
}
void insertatend(node*&head,int data)
{
if(head==NULL)
{
insertathead(head,data);
}
else
{
node*tail=head;
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=new node(data);
}
}
void buildlist(node*&head)
{
int data;
cin>>data;
while(data!=-1)
{
insertatend(head,data);
cin>>data;
}
}
void print(node*head)
{
while(head!=NULL)
{
cout<<head->data<<"->";
head=head->next;
}
}
istream& operator>>(istream &is,node*&head)
{
buildlist(head);
return is;
}
ostream& operator<<(ostream &os,node*head)
{
print(head);
return os;
}
node*midpoint(node*head)
{
if(head==NULL||head->next==NULL)
{
return head;
}
node*slow=head;
node*fast=head->next;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
node*merge(node*a,node*b)
{
if(a==NULL)
{
return b;
}
else if(b==NULL)
{
return a;
}
node*c;
//compare a and b for smaller element
if(a->data < b->data)
{
c=a;
c->next=merge(a->next,b);
}
else if(b->data < a->data)
{
c=b;
c->next=merge(a,b->next);
}
return c;
}
node*mergesort(node*head)
{
if(head==NULL||head->next==NULL)
{
return head;
}
//1. Midpoint
node*mid=midpoint(head);
node*a=head;
node*b=mid->next;
mid->next=NULL;
//2. Recursively Sort
a=mergesort(a);
b=mergesort(b);
//3.Merge a and b
node*c=merge(a,b);
return c;
}
int main()
{
node*head=NULL;
cin>>head;
cout<<head<<endl;
head=mergesort(head);
cout<<head;
return 0;
}