How it works
Scan the unsorted portion to find the minimum. Swap it with the first unsorted element. The sorted boundary moves right by one each pass.
Key Property
// Always exactly N-1 swaps
// Minimizes number of swaps
for i = 0 to n-2:
minIdx = findMin(arr, i, n)
swap(arr[i], arr[minIdx])
// Minimizes number of swaps
for i = 0 to n-2:
minIdx = findMin(arr, i, n)
swap(arr[i], arr[minIdx])
Interactive Visualization
Scanning Current Min Swapping Sorted
Array
Bar Chart
Step 0 of 0
Current Min
—
Comparisons
0
Swaps
0
Sorted
0
Ready. Press Play or Next to start.
✓ Sorted
Speed
C++ — Selection Sort
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; } swap(arr[i], arr[minIdx]); } }
Complexity
Time (All Cases)
O(N²)
Always scans remaining elements.
Space
O(1)
In-place sort.
Stable?
No
Swaps can change relative order of equal elements.
Swaps
O(N)
At most N-1 swaps. Best for minimizing writes.