Sorting / ComparisonBubble SortEasy

Bubble Sort — Swap Adjacent, Bubble Up

Repeatedly compare adjacent elements and swap if out of order. Largest elements "bubble" to the end each pass.

Bubble Sort — Comparison Sort
Not completed
GFG
Practice on GeeksforGeeks: Bubble Sort
Open Problem

How it works

Walk through the array comparing adjacent pairs. If left > right, swap them. Each pass pushes the next largest element to its final position. Repeat until no swaps are needed.

Optimization

// Early termination
if no swaps in a pass:
  array is sorted, stop early
// Each pass shrinks unsorted region by 1
Interactive Visualization
Comparing
Swapping
Sorted
Array
Bar Chart
Step 0 of 0
Pass
0
Comparisons
0
Swaps
0
Sorted
0
Ready. Press Play or Next to start.
āœ“ Sorted
Speed
C++ — Bubble Sort
void bubbleSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break; // optimized
    }
}
Complexity
Time (Worst/Avg)
O(N²)

Nested loops over array.

Time (Best)
O(N)

Already sorted, one pass with early exit.

Space
O(1)

In-place, only temp variable.

Stable?
Yes

Equal elements keep relative order.


šŸ“ Notes

ā–¼