Skip to content

Commit 8dddd72

Browse files
authored
Create bubble_sort_linked_list.cpp
1 parent e12f22e commit 8dddd72

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
//bubble sort iterative
2+
#include <iostream>
3+
class Node
4+
{
5+
public:
6+
int data;
7+
Node *next;
8+
Node(int data)
9+
{
10+
this->data = data;
11+
this->next = NULL;
12+
}
13+
};
14+
15+
using namespace std;
16+
int len(Node *head)
17+
{
18+
Node *temp = head;
19+
int i = 0;
20+
while (temp != NULL)
21+
{
22+
i++;
23+
temp = temp->next;
24+
}
25+
26+
return i;
27+
}
28+
Node *bubbleSort(Node *head)
29+
{
30+
if (head == NULL || head->next == NULL)
31+
return head;
32+
int n = len(head) - 1;
33+
while (n--)
34+
{
35+
Node *prev = NULL;
36+
Node *cur = head;
37+
while (cur->next != NULL)
38+
{
39+
if (cur->data >= cur->next->data)
40+
{
41+
42+
if (prev == NULL)
43+
{
44+
Node *nxt = cur->next;
45+
cur->next = nxt->next;
46+
nxt->next = cur;
47+
prev = nxt;
48+
head = prev;
49+
}
50+
51+
else
52+
{
53+
54+
Node *nxt = cur->next;
55+
prev->next = nxt;
56+
cur->next = nxt->next;
57+
nxt->next = cur;
58+
prev = nxt;
59+
}
60+
}
61+
else
62+
{
63+
64+
prev = cur;
65+
cur = cur->next;
66+
}
67+
}
68+
}
69+
return head;
70+
}
71+
Node *takeinput()
72+
{
73+
int data;
74+
cin >> data;
75+
Node *head = NULL, *tail = NULL;
76+
while (data != -1)
77+
{
78+
Node *newnode = new Node(data);
79+
if (head == NULL)
80+
{
81+
head = newnode;
82+
tail = newnode;
83+
}
84+
else
85+
{
86+
tail->next = newnode;
87+
tail = newnode;
88+
}
89+
cin >> data;
90+
}
91+
return head;
92+
}
93+
void print(Node *head)
94+
{
95+
Node *temp = head;
96+
while (temp != NULL)
97+
{
98+
cout << temp->data << " ";
99+
temp = temp->next;
100+
}
101+
cout << endl;
102+
}
103+
int main()
104+
{
105+
Node *head = takeinput();
106+
head = bubbleSort(head);
107+
print(head);
108+
}

0 commit comments

Comments
 (0)