algorithms · medium
Bubble Sort
Bubble sort repeatedly walks the array swapping adjacent elements that are out of order; after each pass the largest unsorted value settles at the end. It runs in O(n^2) time and O(1) space and is stable. A `swapped` flag lets it stop early — O(n) on already-sorted input — but it's still only suitable for teaching or tiny arrays.
Bubble sort swaps adjacent out-of-order pairs pass after pass, bubbling the largest remaining value to the end each pass; O(n^2) time, O(1) space, stable, with an early-exit flag that makes an already-sorted array O(n).
The code
void bubbleSort(int a[], int n) { for (int i = 0; i < n - 1; ++i) { // up to n-1 passes bool swapped = false; for (int j = 0; j < n - 1 - i; ++j) // last i elements are in place if (a[j] > a[j + 1]) { // adjacent pair out of order? std::swap(a[j], a[j + 1]); // swap them swapped = true; } if (!swapped) break; // no swaps -> already sorted }}What this lesson walks through
- 01Bubble sort — the unsorted array
- 02After pass 1
- 03After pass 2
- 04After pass 3
- 05Sorted
Bubble sort walks the array repeatedly, swapping each adjacent pair that's out of order. After every full pass the largest remaining value has 'bubbled' up to the end.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Bubble Sort and 100+ animated C++ interview lessons.