All algorithms
Sorting

Bubble Sort

The simplest sort — watch the largest value bubble to the end each pass.

TimeO(n²)SpaceO(1)CategorySorting

Bubble Sort repeatedly steps through the array, compares each pair of adjacent elements, and swaps them if they are in the wrong order. After each full pass the largest remaining value has 'bubbled up' to its final position.

It is the first sorting algorithm most people learn because the mechanics are so visible — but it is quadratic, so it is a teaching tool, not a production sort. Seeing every comparison and swap on real data makes the O(n²) cost obvious in a way a textbook cannot.

In AlgoLens you watch your own Bubble Sort run: the array, the two pointers scanning it, and every swap — traced from a real execution, never a canned animation.

The code

bubble_sort.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {5, 2, 9, 1, 7, 3};
    int n = a.size();

    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
            }
        }
    }

    for (int x : a) cout << x << ' ';
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Bubble Sort

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going