Skip to content

Commit 95cb299

Browse files
authored
Update Merge Sort.cpp
1 parent 49eeedd commit 95cb299

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

13- Linked Lists/Merge Sort.cpp

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,34 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
struct node{
4+
int data;
5+
node* next;
6+
};
7+
void insert(int data,node** head){
8+
if(*head==NULL){
9+
node* n=new node;
10+
n->data=data;
11+
n->next=NULL;
12+
*head=n;
13+
return;
14+
}
15+
node* current=*head;
16+
while(current->next!=NULL){
17+
current=current->next;
18+
}
19+
node* n=new node;
20+
n->data=data;
21+
n->next=NULL;
22+
current->next=n;
23+
}
24+
void print(node* head){
25+
node* current=head;
26+
while(current!=NULL){
27+
cout<<current->data<<" ";
28+
current=current->next;
29+
}
30+
cout<<endl;
31+
}
132
node* split(node* head){
233
node* hare=head;
334
node* tortoise=head;
@@ -36,5 +67,17 @@ node* mergeSort(node* head){
3667
if(!head || head->next==NULL){
3768
return head;
3869
}
39-
return converge(mergeSort(split(head)),mergeSort(head));
70+
node* node1=head;
71+
node* node2=split(head);
72+
return converge(mergeSort(node1),mergeSort(split(head)));
73+
}
74+
int main(){
75+
node* head=NULL;
76+
insert(2,&head);
77+
insert(4,&head);
78+
insert(3,&head);
79+
insert(1,&head);
80+
print(head);
81+
head=mergeSort(head);
82+
print(head);
4083
}

0 commit comments

Comments
 (0)