Learn, Visualize, and Understand Bubble Sort Algorithm
Bubble Sort is a simple sorting algorithm that repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. The largest elements "bubble up" to the end of the array with each pass.
Sorting students by height: Imagine students standing in a line.
This is exactly how bubble sort works!
Step 1: Start from the beginning of the array
Step 2: Compare adjacent elements (arr[i] and arr[i+1])
Step 3: If they're in wrong order, swap them
Step 4: Move to next pair and repeat
Step 5: After each pass, largest unsorted element reaches its correct position
Step 6: Repeat until no swaps are needed
Array: [5, 1, 4, 2, 8]
Pass 1:
Pass 2:
Pass 3: No swaps needed → Array is sorted!
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(n) | Array already sorted (optimized version) |
| Average Case | O(n²) | Elements in random order |
| Worst Case | O(n²) | Array sorted in reverse order |
| Space Complexity | O(1) | Only uses constant extra space |
Watch how bubble sort compares and swaps adjacent elements to sort the array
See the C code and watch how it executes step-by-step
#include <stdio.h>
// Bubble Sort Function - Sorts array in ascending order
void bubbleSort(int arr[], int n) {
// Outer loop - number of passes
for (int i = 0; i < n-1; i++) {
int swapped = 0; // Flag to detect if swap occurred
printf("Pass %d:\\n", i+1);
// Inner loop - compare adjacent elements
for (int j = 0; j < n-i-1; j++) {
printf(" Comparing arr[%d]=%d and arr[%d]=%d\\n",
j, arr[j], j+1, arr[j+1]);
// If elements are in wrong order, swap them
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = 1;
printf(" → Swapped!\\n");
}
}
// If no swaps, array is sorted
if (!swapped) {
printf("No swaps in this pass. Array is sorted!\\n");
break;
}
printf("\\n");
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n\\n");
bubbleSort(arr, n);
printf("\\nSorted array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
return 0;
}