Sorting
Selection Sort
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
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
- In C++, the input is a
std::vector<int>initialized as{5, 1, 4, 2, 8}andnis copied fromstatic_cast<int>(arr.size())for the loop bounds. - Both scan indexes are
int:iruns whilei < n - 1, andjscans fromi + 1ton - 1, keeping eacharr[j]andarr[minIdx]read inside the vector. int minIdx = itracks the current minimum slot. The comparisonarr[j] < arr[minIdx]mutates only that scalar index until the pass ends.- Swaps are manual and guarded by
if (minIdx != i):int tmp = arr[i], then assignments toarr[i]andarr[minIdx]. The checked source does not callstd::swap. - The trace shows pass
i=0swapping indexes0and1, passi=1swapping indexes1and3, then two no-swap passes with the array already[1, 2, 4, 5, 8]. - Output is streamed with
std::cout, asize_tprint loop, comma separators, andstd::endl. Visible allocation is the vector storage; mutation is vector element assignment plus scalarminIdxandtmp.
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.