-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesorting.cpp
95 lines (75 loc) · 1.48 KB
/
mergesorting.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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void push(Node **head,int val){
Node *ptr=new Node();
ptr->next = *head;
ptr->data=val;
*head=ptr;
}
void lltrav(Node *head){
Node *ptr=head;
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
Node *merging(Node *a,Node *b){
Node *result=NULL;
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
if(a->data <= b->data){
result = a;
result->next = merging(a->next,b);
}else{
result = b;
result->next = merging(a,b->next);
}
return result;
};
void splitting(Node *source,Node **frontside,Node **backside){
Node *slow=source;
Node *fast=source->next;
while(fast!=NULL){
fast=fast->next;
if(fast!=NULL){
slow=slow->next;
fast=fast->next;
}
}
*frontside=source;
*backside=slow->next;
slow->next = NULL;
}
void mergesort(Node **headref){
Node *head = *headref;
Node *a;
Node *b;
if ((head == NULL) || (head->next == NULL)) {
return;
}
splitting(head,&a,&b);
mergesort(&a);
mergesort(&b);
*headref = merging(a,b);
}
int main(){
Node *head=NULL;
push(&head,4);
push(&head,67);
push(&head,12);
push(&head,23);
push(&head,1);
push(&head,9);
lltrav(head);
mergesort(&head);
lltrav(head);
return 0;
}