All algorithms
Sorting

Selection Sort

Find the smallest remaining value each pass and swap it into place.

TimeO(n²)SpaceO(1)CategorySorting

Selection Sort splits the array into a sorted front and an unsorted rest. Each pass scans the whole unsorted part for the minimum and swaps it to the boundary — so after k passes the first k positions are final and never move again.

It always performs exactly n−1 swaps, far fewer than Bubble Sort, which matters when writing is expensive. Its comparison count, however, is O(n²) regardless of input — sorted data costs the same as reversed data.

The scan is the whole story: one pointer marks the boundary, another hunts for the minimum. AlgoLens draws both moving across the array so the quadratic cost is visible rather than asserted.

The code

selection_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++) {
        int best = i;
        for (int j = i + 1; j < n; j++) {
            if (a[j] < a[best]) best = j;
        }
        swap(a[i], a[best]);
    }

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

Now run your own Selection 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