Bubble Sort a Linked List in C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void swap(struct Node a, struct Node b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
void bubbleSort(struct Node* head) {
int swapped;
struct Node* ptr1;
struct Node* lptr = NULL;
if (head == NULL)
return;
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 3;
head->next = second;
second->data = 2;
second->next = third;
third->data = 1;
third->next = NULL;
printf("Linked list before sorting: \n");
printList(head);
bubbleSort(head);
printf("\nLinked list after sorting: \n");
printList(head);
return 0;
}