Skip to content

Commit 8d8de2c

Browse files
Create bubble sort.c
1 parent f9d42bb commit 8d8de2c

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

bubble sort.c

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#include <stdio.h>
2+
3+
//Represent a node of the singly linked list
4+
struct node{
5+
int data;
6+
struct node *next;
7+
};
8+
9+
//Represent the head and tail of the singly linked list
10+
struct node *head, *tail = NULL;
11+
12+
//addNode() will add a new node to the list
13+
void addNode(int data) {
14+
//Create a new node
15+
struct node *newNode = (struct node * )malloc( sizeof(struct node));
16+
newNode->data = data;
17+
newNode->next = NULL;
18+
19+
//Checks if the list is empty
20+
if(head == NULL) {
21+
//If list is empty, both head and tail will point to new node
22+
head = newNode;
23+
tail = newNode;
24+
}
25+
else {
26+
//newNode will be added after tail such that tail's next will point to newNode
27+
tail->next = newNode;
28+
//newNode will become new tail of the list
29+
tail = newNode;
30+
}
31+
}
32+
33+
//sortList() will sort nodes of the list in ascending order
34+
void sortList() {
35+
//Node current will point to head
36+
struct node *current = head, *index = NULL;
37+
int temp;
38+
39+
if(head == NULL) {
40+
return;
41+
}
42+
else {
43+
while(current != NULL) {
44+
//Node index will point to node next to current
45+
index = current->next;
46+
47+
while(index != NULL) {
48+
//If current node's data is greater than index's node data, swap the data between them
49+
if(current->data > index->data) {
50+
temp = current->data;
51+
current->data = index->data;
52+
index->data = temp;
53+
}
54+
index = index->next;
55+
}
56+
current = current->next;
57+
}
58+
}
59+
}
60+
61+
//display() will display all the nodes present in the list
62+
void display() {
63+
//Node current will point to head
64+
struct node *current = head;
65+
if(head == NULL) {
66+
printf("List is empty \n");
67+
return;
68+
}
69+
while(current != NULL) {
70+
//Prints each node by incrementing pointer
71+
printf("%d ", current->data);
72+
current = current->next;
73+
}
74+
printf("\n");
75+
}
76+
77+
int main()
78+
{
79+
int n,data;
80+
scanf("%d",&n);
81+
//Adds data to the list
82+
for(int i=0;i<n;i++)
83+
{
84+
scanf("%d",&data);
85+
addNode(data);
86+
}
87+
88+
//Displaying original list
89+
90+
91+
92+
//Sorting list
93+
sortList();
94+
95+
//Displaying sorted list
96+
97+
display();
98+
99+
return 0;
100+
}

0 commit comments

Comments
 (0)