Selection sort repeatedly finds the smallest unsorted element and swaps it into its correct position. After each pass, one more element is locked into place at the start of the array.
The algorithm:
- Start at the beginning. Find the smallest element in the array.
- Swap it with the first element.
- Now the first position is sorted; the rest is unsorted.
- Find the smallest element in the remaining unsorted portion. Swap with the second element.
- Repeat until the entire array is sorted.
void selectionSort(int arr[], int n) {
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]);
}
}Big O
- Best case: . Even an already-sorted input requires comparisons because the algorithm doesn’t know when to stop early — it always scans the rest of the array for each position.
- Average case: .
- Worst case: .
The number of comparisons is regardless of input.
The number of swaps is exactly — one per outer iteration. This is one of selection sort’s saving graces: minimal swaps. If swapping is expensive (e.g., moving large records), this matters.
When to use it
Almost never, in serious code. Selection sort is mostly a teaching tool. Practical sorts (quicksort, merge sort, heap sort) all run in , which beats for any non-trivial input size.
The one place selection-style ideas survive: partial sorting (find the K smallest items), where modified selection beats fully sorting just to take the first K.
Vs other O(n²) sorts
| Sort | Comparisons | Swaps | Stable? |
|---|---|---|---|
| Selection | No | ||
| Bubble | up to | up to | Yes |
| Insertion | up to | up to | Yes |
Selection makes the fewest swaps but doesn’t preserve relative order of equal elements (not stable). Bubble sort and insertion sort are both stable.
A subtlety: the array form of selection sort shown above is not stable, because swapping arr[i] with arr[minIdx] jumps a possibly-different element over the elements between them, scrambling their order relative to equal keys. A linked-list version that moves the minimum node to the sorted prefix (rather than swapping values) is stable, because moving doesn’t disturb the order of the elements left behind. This is one of the few cases where a linked-list reimplementation changes the algorithm’s stability.
For the related sort that uses a heap (much faster), see Heap sort. For more efficient general-purpose sorts, see Quick sort and Merge sort.