/
Linked_List_Bubble_Sort.c
97 lines (88 loc) · 1.54 KB
/
Linked_List_Bubble_Sort.c
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
#include<stdio.h>
#include<malloc.h>
/* Link list node */
typedef struct node
{
int data;
struct node *next;
}node;
node *head=NULL;
/*Function to create a linked list*/
void createll()
{
int i,n;
node *tail; // keeps track of the last element
tail=head; //atm head is the last element
printf("Enter the size:");
scanf("%d",&n);
printf("Enter the data:\n");
for(i=1;i<=n;i++)
{
node *newn;
newn=(node*)malloc(sizeof(node)); //creates a new node in every iteration
scanf("%d",&newn->data);
newn->next = NULL;
if(head==NULL)
{
head=newn;
tail=head;
}
else
{
tail->next=newn; //linking the previous last element to new last element
tail=newn; //making the new element as the last element
}
}
}
/* Function to print linked list */
void display()
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
/* function to swap data of two nodes a and b*/
void swap(node *a,node *b)
{
int temp = a->data;
a->data = b->data;
b->data = temp;
}
/*Function to bubble sort*/
void bubble()
{
int ctr,n=1;
node *t1,*t2;
t1=head;
do
{
ctr=0;
t2=head;
while(t2->next!=NULL)
{
if(t2->data > t2->next->data)
{
swap(t2,t2->next);
ctr=1;
}
t2=t2->next;
}
t1=t1->next;
printf("After iteration %d : ",n);
display();
n++;
}while(t1->next!=NULL && ctr);
}
void main()
{
createll();
printf("\nBefore Sorting: ");
display();
bubble();
printf("\nAfter Sorting: ");
display();
}