Repeatedly find the index of the smallest remaining element and swap it into the next "sorted prefix" slot. Unlike bubble sort, only one swap per pass.

Algorithm

Canonical input [5, 1, 4, 2, 8] finishes after four passes, with two real swaps (passes 0 and 1) and two skip-swap passes (minIdx == i). Final array [1, 2, 4, 5, 8].

Basic Implementation

basic.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> arr = {5, 1, 4, 2, 8};
    int n = static_cast<int>(arr.size());
    for (int i = 0; i < n - 1; ++i) {
        int minIdx = i;
        for (int j = i + 1; j < n; ++j) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j;
            }
        }
        if (minIdx != i) {
            int tmp = arr[i];
            arr[i] = arr[minIdx];
            arr[minIdx] = tmp;
        }
    }
    std::cout << "[";
    for (size_t i = 0; i < arr.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << arr[i];
    }
    std::cout << "]" << std::endl;
    return 0;
}

Complexity

  • Time: O(n^2) regardless of input order
  • Space: O(1)
  • Stable: no
  • Swap count: at most n-1

Implementation notes

  • C++: same loop shape as Python / Java / JavaScript. The if (minIdx != i) guard is the canonical skip-swap variant from the lesson spec.
  • An int minIdx = i; keeps the running-minimum invariant visible; a raw int tmp swap mirrors the bubble-sort lesson.
  • The replay highlights the current minIdx distinctly from the scanning index j so the viewer sees the running minimum travel.
running minimum `minIdx` tracks the index of the smallest value seen in `arr[i..]`.
sorted prefix After each pass, `arr[0..i]` is the final sorted prefix.