forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort in linkedlist
67 lines (57 loc) · 1.53 KB
/
MergeSort in linkedlist
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
class Solution{
public:
//Function to sort the given linked list using Merge Sort.
Node* findMid(Node *head){
Node* slow=head;
Node* fast=head->next;
while(fast && fast->next){
slow=slow->next;
fast=fast->next;
}
return slow;
}
Node* merge(Node* left,Node* right){
if(left==NULL)
return right;
if(right==NULL)
return left;
Node *ans=new Node(-1);
Node* temp=ans;
while(left!=NULL && right!=NULL){
if(left->data < right->data){
temp->next=left;
temp=left;
left=left->next;
}
else{
temp->next=right;
temp=right;
right=right->next;
}
}
while(left!=NULL){
temp->next=left;
temp=left;
left=left->next;
}
while(right!=NULL){
temp->next=right;
temp=right;
right=right->next;
}
ans=ans->next;
return ans;
}
Node* mergeSort(Node* head) {
// your code here
if(head==NULL || head->next== NULL)
return head;
Node* mid=findMid(head);
Node* left=head;
Node* right=mid->next;
mid->next=NULL;
left=mergeSort(left);
right=mergeSort(right);
Node *result=merge(left,right);
return result;
}