-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Linked_List_Bubble_Sort.cpp
116 lines (92 loc) · 1.87 KB
/
Linked_List_Bubble_Sort.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
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
} *head = NULL;
bool Is_List_Empty()
{
if(head == NULL)
return true;
return false;
}
void Insert_At_End(int value)
{
node *temp = new node, *current = head;
temp -> data = value;
temp -> next = NULL;
if(Is_List_Empty())
{
head = temp;
return ;
}
while(current -> next != NULL)
current = current -> next;
current -> next = temp;
}
void Bubble_Sort(){
int cnt = 0;
node *start = head;
node *curr = NULL;
node *trail = NULL;
node *tmp = NULL;
//get cnt(size) of linked list
while(start != NULL){
start = start->next;
++cnt;
}
for (int i = 0; i < cnt; ++i){
//set curr and trail at the start node
curr = trail = head;
while(curr->next != NULL){
//compares curr and its next
if (curr->data > curr->next->data){
//swaps pointers for curr & curr->next
tmp = curr->next;
curr->next = curr->next->next;
tmp->next = curr;
//setup pointers for the head and trail if applicable
if(curr ==head)
head = trail = tmp;
else
trail->next = tmp;
curr = tmp;
}
//advance pointers
trail = curr;
curr = curr->next;
}
}
}
void Print_Linked_List()
{
if(Is_List_Empty())
{
cout << "List is Empty" << endl;
return ;
}
node *current = head;
while(current -> next != NULL)
{
cout << current -> data << " -> ";
current = current -> next;
}
cout << current -> data << endl;
}
int main()
{
int i;
cout << "Before Bubble Sort ";
for(i = 10; i > 5; --i)
Insert_At_End(i);
Print_Linked_List();
Bubble_Sort();
cout << "After Bubble Sort ";
Print_Linked_List();
return 0;
}
/* Output
Before Bubble Sort 10 -> 9 -> 8 -> 7 -> 6
After Bubble Sort 6 -> 7 -> 8 -> 9 -> 10
*/