-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergesortinLinkedList.cpp
More file actions
127 lines (123 loc) · 2.04 KB
/
MergesortinLinkedList.cpp
File metadata and controls
127 lines (123 loc) · 2.04 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
121
122
123
124
125
126
127
#include<iostream>
using namespace std;
class node
{
public:
int data;
node * next;
node(int d)
{
data = d;
next = NULL;
}
};
void insertattail(node*&head , int data)
{
node *temp = head;
if (head == NULL)
{
head = new node(data);
return;
}
while(temp->next != NULL)
{
temp = temp -> next;
}
node *n = new node(data);
temp->next = n;
return;
}
void build(node*&head)
{
int data;
cin>>data;
while(data != -1)
{
insertattail(head,data);
cin>>data;
}
}
void print(node*&head)
{
node* tail = head;
while(tail != NULL)
{
cout<<tail->data<<"->";
tail = tail -> next;
}
cout<<endl;
}
//Using operator overloading to input and output in Linked List
istream& operator>>(istream &is, node*&head)
{
build(head);
return is;
}
ostream& operator<<(ostream &os, node*&head)
{
print(head);
return os;
}
node *midpoint(node*head)
{
node *slow = head;
node *fast = head->next; // updated
while(fast != NULL && fast->next != NULL)
{
slow = slow ->next;
fast = fast -> next ->next;
}
return slow;
}
node *merge(node*a , node*b)
{
if(a == NULL)
{
return b;
}
if(b == NULL)
{
return a;
}
node *c;
if (a->data < b->data)
{
c = a;
c->next = merge(a->next,b);
}
else
{
c = b;
c->next = merge(a,b->next);
}
return c;
}
node* mergesort(node*head)
{
//Base Case
if(head==NULL || head->next ==NULL)
{
return head;
}
//Recursive case
//1. Mid Point
node *mid = midpoint(head);
//Make 2 Linked List (Dividing the Linked List)
node *a = head;
node *b = mid->next;
mid->next = NULL;
//2. Recursively Sort
a = mergesort(a);
b = mergesort(b);
//3. Merging the two arrays (We are not creating any other Linked List, we are creating a pointer variable)
node *c = merge(a,b);
return c;
}
int main()
{
node *head = NULL;
cin>>head;
cout<<head;
head = mergesort(head);
cout<<head; // Printing using operator overloading
}