-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedMergeSort.cpp
121 lines (100 loc) · 1.92 KB
/
linkedMergeSort.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
@chiranjeevi
Date : 21-May-17
#include <iostream>
#include <random>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}node;
void print(node *ptr){
while(ptr!=NULL){
cout<<ptr->data<<"->";
ptr=ptr->next;
}
cout<<endl;
}
node *createNode(int num){
node *newnode = new node;
newnode->data=num;
newnode->next=NULL;
return newnode;
}
void insert(node **ptr2head, node **ptr2tail, int num){
node *tempnode=createNode(num);
if(*ptr2head==NULL){
*ptr2head=tempnode;
*ptr2tail=tempnode;
}
else{
(*ptr2tail)->next=tempnode;
*ptr2tail=(*ptr2tail)->next;
}
}
node *mergeLists(node *ptr1, node *ptr2){
node *head=NULL,*tail=NULL;
while(ptr1!=NULL || ptr2!=NULL){
if(ptr1==NULL){
tail->next=ptr2;
break;
}
else if(ptr2==NULL){
tail->next=ptr1;
break;
}
else if(ptr1->data>ptr2->data){
if(head==NULL){
head=tail=ptr2;
}
else{
tail->next=ptr2;
tail=tail->next;
}
ptr2=ptr2->next;
tail->next=NULL;
}
else{
if(head==NULL){
head=tail=ptr1;
}
else{
tail->next=ptr1;
tail=tail->next;
}
ptr1=ptr1->next;
tail->next=NULL;
}
}
return head;
}
node *linkedMergeSort(node *ptr){
if(ptr->next==NULL)
return ptr;
node *ptr1=ptr,*ptr2=ptr;
while(ptr2->next!=NULL && ptr2->next->next!=NULL){
ptr1=ptr1->next;
ptr2=ptr2->next->next;
}
node *temp=ptr1->next;
ptr1->next=NULL;
ptr1=temp;
ptr=linkedMergeSort(ptr);
ptr1=linkedMergeSort(ptr1);
ptr=mergeLists(ptr,ptr1);
return ptr;
}
int main(){
int n,range;
cin>>n>>range;
node *head=NULL,*tail=NULL;
default_random_engine gen;
uniform_int_distribution<int> dist(1,range);
for(int i=0; i<n; i++)
insert(&head,&tail,dist(gen));
cout<<"Input list:"<<endl;
print(head);
head=linkedMergeSort(head);
cout<<"Sorted list:"<<endl;
print(head);
}