Implement Bubble Sort in C with optimized early exit flags. Includes step-by-step trace, memory comparisons, and time complexity analysis.
How Bubble Sort Works
Bubble Sort is a comparison-based sorting algorithm where adjacent elements are repeatedly compared and swapped if they are in the wrong order. With each pass through the array, the largest unsorted element "bubbles up" to its correct position at the end.
Optimized C Implementation
Using a swapped boolean flag allows the algorithm to exit early in O(n) time if the array is already sorted:
c (ISO Standard)#include <stdio.h> #include <stdbool.h> void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { bool swapped = false; /* Last i elements are already in place */ for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } /* If no elements were swapped, array is sorted */ if (!swapped) { break; } } } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int data[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(data) / sizeof(data[0]); printf("Original array:\n"); printArray(data, n); bubbleSort(data, n); printf("\nSorted array in ascending order:\n"); printArray(data, n); return 0; }
Expected Output
text (ISO Standard)Original array: 64 34 25 12 22 11 90 Sorted array in ascending order: 11 12 22 25 34 64 90
Complexity Analysis
- Best Case Time:
O(n)(When the input array is already sorted). - Average & Worst Case Time:
O(n²)(When elements are in reverse order). - Auxiliary Space:
O(1)(In-place sorting algorithm). - Stability: Stable (Equal elements retain their original relative order).
Related Guides & Practical Examples
- Learn how to swap pointers cleanly in Swap Two Numbers in C.
- Master array indexing and bounds in Arrays in C Programming.
- Explore our entire Examples Code Library.