Code for Bubble Sort using Linked List
This code is designed to implement Bubble Sort Using Linked List. In this code we have created a linked list then displayed the linked list. After that we have performed Bubble Sort Using Linked List and then displayed the sorted linked list. This code will help an programmer to understand basics of linked list and as well how to access value and addresses of next nodes.
For Such more codes click here and for video tutorial click here.
#include
#include
typedef struct linked {
int val;
struct linked * next;
}
lnk;
lnk * create();
void bubblesort(lnk * );
void disp(lnk * );
void main() {
lnk * h;
printf("\n\nEnter the values (0 to exit) : ");
h = create();
printf("\n\nValues in the linked list before sorting are : ");
disp(h);
bubblesort(h);
printf("\n\nValues in the linked list after sorting are : ");
disp(h);
}
lnk * create() {
lnk * temp, * ptr, * h = NULL;
int v;
while (1) {
scanf("%d", & v);
if (v == 0)
return h;
temp = (lnk * ) malloc(sizeof(lnk));
temp -> val = v;
temp -> next = NULL;
if (h == NULL)
h = temp;
else
ptr -> next = temp;
ptr = temp;
}
}
void disp(lnk * h) {
while (h != NULL) {
printf("%d,", h -> val);
h = h -> next;
}
}
void bubblesort(lnk * h) {
int v;
lnk * ptr, * loc;
loc = h;
while (h != NULL) {
ptr = loc;
while (ptr -> next != NULL) {
if (ptr -> val > ptr -> next -> val) {
v = ptr -> val;
ptr -> val = ptr -> next -> val;
ptr -> next -> val = v;
}
ptr = ptr -> next;
}
h = h -> next;
}
}