Sorting algorithms are essential in programming, and bubble sort is one of the simplest to learn. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. In this blog post, we’ll explore how to implement bubble sort in C with a clear explanation and working code.
What is Bubble Sort?
Bubble sort works by comparing each pair of adjacent elements and swapping them if they are not in the correct order. This process repeats until the entire array is sorted. It’s called “bubble” sort because larger elements “bubble” to the end of the array in each pass.
Bubble Sort Algorithm Steps:
- Loop through the array.
- Compare adjacent elements.
- Swap if needed.
- Repeat until the array is sorted.
Bubble Sort in C – Full Program:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array using Bubble Sort:\n");
printArray(arr, n);
return 0;
}
Why Learn Bubble Sort in C?
- Easy to understand for beginners.
- Helps grasp the concept of nested loops.
- Useful for small datasets and teaching sorting logic.
While bubble sort isn’t efficient for large datasets (O(n²) complexity), it’s a great starting point in your data structures and algorithms journey.