-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLinkedlistSort.cpp
More file actions
79 lines (66 loc) · 1.43 KB
/
LinkedlistSort.cpp
File metadata and controls
79 lines (66 loc) · 1.43 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
#include<iostream>
int pass = 0;
using namespace std;
class Node{
public:
int data;
Node *next;
};
Node* swapping(Node* p1, Node* p2){
int temp = p1->data;
p1->data = p2->data;
p2->data = temp;
}
Node* display(Node* head, int n){
for(int i=0;i<n;i++){
cout<<head->data<<" ";
head = head->next;
}
}
void sort(Node *head, int n){
int swaps = 0;
Node *ptr1 = head;
Node *ptr2 = ptr1->next;
for(int i = 0;i<n;i++){
for(int j=0;j<n-i-1;j++){
if(ptr1->data > ptr2->data) {
swapping(ptr1, ptr2);
swaps = 1;
}
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
ptr1 = head;
ptr2 = ptr1->next;
if(!swaps)
break;
pass = pass+1;
}
}
Node* insert(Node *head, int n){
Node *ptr = head;
for(int i = 0;i<n;i++){
cout<<"Enter the value "<<i+1<<" : ";
cin>>ptr->data;
if(i==n-1){
break;
}
ptr->next = new Node();
ptr = ptr->next;
}
ptr->next = NULL;
}
int main(){
int n, val;
Node* head = NULL;
head = new Node();
cout<<"Enter the no of elements: ";
cin>>n;
insert(head, n);
cout<<"Linkedlist before sorting : ";
display(head, n);
cout<<"\nLinkedlist after sorting : ";
sort(head, n);
display(head, n);
cout<<"\nNo. of passes : "<<pass;
}