Selection Sort
Legend
- • Numbers show element values
- • Bottom labels show array indices
- • Colors indicate current operation
- • Height represents value magnitude
Inspector
Legend
- • Numbers show element values
- • Bottom labels show array indices
- • Colors indicate current operation
- • Height represents value magnitude
Inspector
Reference implementation of Selection Sort. Select a language tab to view and copy the code.
void selection_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
if (min_idx != i) {
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}#include <vector>
#include <algorithm>
void selectionSort(std::vector<int>& arr) {
int n = static_cast<int>(arr.size());
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
if (min_idx != i)
std::swap(arr[i], arr[min_idx]);
}
}public static void selectionSort(int[] arr) {
int n = arr.length;
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 temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
}def selection_sort(arr: list[int]) -> None:
n = len(arr)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
if min_idx != i:
arr[i], arr[min_idx] = arr[min_idx], arr[i]function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIdx = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
}
}Python — Code Walkthrough
Type hints and in-place return
arr: list[int]) -> NoneThe function modifies the list in place and returns None. Python lists are mutable objects; passing arr gives access to the same underlying list.
Outer range
for i in range(n - 1)Iterates over every position that needs to be filled. range(n − 1) stops one before the last element because the final element is already in place after all preceding passes.
Track minimum with a variable
min_idx = iStores the index of the smallest element found so far in the unsorted portion. Updated inside the inner loop when a smaller element is encountered.
Inner range starts at i+1
for j in range(i + 1, n)Only scans the unsorted part of the array. range(i + 1, n) generates indices i+1 through n−1, skipping the already-sorted prefix.
Conditional tuple swap
if min_idx != i: arr[i], arr[min_idx] = arr[min_idx], arr[i]Skips the swap if the minimum is already in position. Python's simultaneous assignment makes the swap a one-liner with no temp variable.