How do you implement bubble sort in C and what optimizations can be applied?
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Each pass "bubbles" the largest unsorted element to its correct position.
Basic version: Two nested loops, O(n^2) always.
Optimization 1 -- Early termination: If no swaps occur in a pass, the array is already sorted. Add a swapped flag. Best case becomes O(n) for nearly sorted data.
Optimization 2 -- Shrinking range: After each pass, the last element is in place. Reduce the inner loop range by 1 each pass.
Time: O(n^2) worst/average, O(n) best (with flag). Space: O(1). Stable: Yes (equal elements maintain relative order).
BubbleSort(arr, n):
for i = 0 to n-2:
swapped = false
for j = 0 to n-2-i:
if arr[j] > arr[j+1]:
swap(arr[j], arr[j+1])
swapped = true
if not swapped: break // already sorted
#include <stdio.h>
/* Optimized bubble sort with early termination */
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
/* Swap */
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
if (!swapped) break; /* array is sorted */
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main(void) {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before: ");
printArray(arr, n);
bubbleSort(arr, n);
printf("After: ");
printArray(arr, n); /* 11 12 22 25 34 64 90 */
return 0;
}
- •Repeatedly swap adjacent out-of-order elements
- •O(n^2) worst/average, O(n) best with early termination flag
- •Stable sort: equal elements keep their original order
- •O(1) space -- in-place sorting
- •Inner loop range shrinks by 1 each pass (last i elements are sorted)
- •Without the swapped flag, bubble sort is always O(n^2) even for sorted input
- •Bubble sort is almost never used in production -- it is the slowest O(n^2) sort in practice
- •n-1-i in inner loop: forgetting -i means extra unnecessary comparisons
- •Confusing bubble sort with selection sort -- bubble sort swaps adjacent, selection finds minimum