Sorting an array using Bubble Sort
What you'll learn: How to organize the elements of an array in ascending order by repeatedly swapping adjacent items until the largest values "bubble up" to the end.
The "Heavy Lifting" Concept
Imagine you have a row of people of different heights standing in a line, and you want to arrange them from shortest to tallest. You start at the beginning of the line and compare the first two people. If the person on the left is taller than the person on the right, they swap places. Then, you move to the next pair and repeat the process.
By the time you reach the end of the line, the tallest person has naturally "bubbled" to the very last position. Because one pass only guarantees that the largest item is in its correct spot, you have to repeat this entire process for the rest of the line until everyone is in order.
Implementing the Logic
In C, we achieve this using nested loops. The outer loop tracks how many passes we need to make, while the inner loop performs the actual comparisons and swaps between adjacent elements (array[j] and array[j + 1]).
#include <stdio.h>
int main() {
int arr[] = {5, 2, 8, 1, 9};
int n = 5;
// Outer loop for each pass
for (int i = 0; i < n - 1; i++) {
// Inner loop to compare adjacent elements
for (int j = 0; j < n - i - 1; j++) {
// If the left element is bigger, swap them
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Array is now: 1, 2, 5, 8, 9
return 0;
}
Why the loops look different
You might notice the inner loop runs until n - i - 1. This is an optimization: after the first pass, the largest number is already at the end. After the second pass, the two largest are set. We don’t need to re-check the end of the array because those elements are already sorted.
While Bubble Sort isn't the fastest algorithm for massive datasets, it is the most intuitive way to understand how computers move data step-by-step to create order out of chaos.
Key takeaway
Bubble Sort works by repeatedly swapping adjacent elements so that the largest unsorted value moves to its correct position at the end of the array with every pass.