Why Sorting Matters, and Bubble Sort

Why sort?

Sorted data is easier to work with: binary search needs it, duplicates end up side by side, and the smallest and largest items sit at the ends.

Bubble sort

Compare neighbours and swap them if they're in the wrong order. After one pass the biggest item has “bubbled” to the end. Repeat.

Think of it like this: Lining up children by height: walk along the line swapping any neighbours where the taller one is in front.

#include <iostream>
#include <vector>
using namespace std;

void show(const vector<int>& v) {
    for (int x : v) cout << x << ' ';
    cout << endl;
}

int main() {
    vector<int> v = {5, 1, 4, 2, 8};
    int n = v.size();
    for (int done = 0; done < n - 1; done++) {
        bool swapped = false;
        for (int i = 0; i < n - 1 - done; i++) {
            if (v[i] > v[i + 1]) {
                swap(v[i], v[i + 1]);
                swapped = true;
            }
        }
        cout << "after pass " << done + 1 << ": ";
        show(v);
        if (!swapped) break;          // already sorted
    }
    return 0;
}

Output

after pass 1: 1 4 2 5 8 
after pass 2: 1 2 4 5 8 
after pass 3: 1 2 4 5 8 
CaseTime
Already sorted (with the swapped check)O(n)
Average / worstO(n²)
Extra spaceO(1)
HOME LABS COMMUNITY DASHBOARD