What does it solve?
Sorts an array by dividing it into a sorted region (left) and an unsorted region (right). On each pass it scans the unsorted region to find the minimum element.
That minimum is then swapped into the front of the unsorted region, growing the sorted region by one element each pass — until the whole array is sorted.
The core idea
// for each boundary position i:
minIdx = i
for j = i+1 to n-1:
if arr[j] < arr[minIdx]:
minIdx = j
swap(arr[i], arr[minIdx])
minIdx = i
for j = i+1 to n-1:
if arr[j] < arr[minIdx]:
minIdx = j
swap(arr[i], arr[minIdx])
Complexity
Time complexity
O(N²)
Always scans the remaining unsorted region for each of the N positions — same in best, average, and worst case.
Space complexity
O(1)
Sorts in place — only a few index variables are needed beyond the input array.
Examples & edge cases
Live animation
Comparing (j)
Current minimum
Boundary (i)
Sorted
Step — of —
Boundary (i)
—
—
Comparing (j)
—
—
Current min
—
at index —
Swaps so far
—
total
Select an example and press Play to start.
✓ Sorted
Speed
Medium
Step-by-step table
| Step | i | j | Action | Array state | Note |
|---|
C++ implementation
selection_sort.cpp
#include <bits/stdc++.h> using namespace std; void selectionSort(vector<int>& arr) { int n = 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; // found a new minimum } } if (minIdx != i) { swap(arr[i], arr[minIdx]); // place min at boundary } } } int main() { vector<int> arr = {29, 10, 14, 37, 13}; selectionSort(arr); for (int x : arr) cout << x << " "; cout << "\n"; return 0; }
My Notes