Selection sort
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Selection sort repeatedly finds the smallest remaining item and places it next in line. It makes very few swaps, which matters when writing data is costly. It is slow for large lists but simple and predictable.
Practical use cases
- Web app: Pick the top 3 of a short list. A dashboard shows the three cheapest plans out of a dozen. Running selection three times, each time picking the smallest remaining price, gives the answer without sorting the whole list. The code is tiny and the dashboard needs no extra library.
- Web app: Sorting when each move is costly. Imagine a tool that must physically rewrite rows on a slow storage device or send each move over the network. Selection sort does at most one swap per round, so it writes far less than other simple sorts. That saves time when each write is the expensive part.
- System: Tiny embedded devices. Small controllers in appliances have almost no memory for fancy code. Selection sort needs no extra space, and the number of swaps is known in advance, so engineers sometimes pick it for sorting a few sensor values on a device with very little room.
The story: The Laddoo Tray
Grandpa Bhaskar was in charge of the sweets at Zoya's cousin's wedding. A big pile of laddoos had arrived, all different sizes, and the guests would be served from a tray where the smallest laddoo must come first, then the next smallest, and so on.
Mira watched him work. He did not shuffle laddoos left and right. He scanned the whole pile with his eyes, picked out the smallest one, and placed it at the start of the tray. Then he scanned the remaining pile, picked the smallest again, and put it in the second spot.
"Why do you look at everything every time?" asked Mira. "Because", said Grandpa, "the smallest of what is left has to be somewhere in the pile. Once a laddoo reaches its tray spot, I never touch it again."
That patient habit has a name: selection sort. Select the smallest, place it, shrink the pile, repeat. It is slow when the pile is huge, but it is simple, and it makes very few moves.
How to spot this problem, and where you need it
You need a sorted order for a small list where the number of swaps or writes matters more than the number of comparisons, or you only need the first few smallest items.
Signs you need it
- Moving or writing an item is much more expensive than looking at it, for example flash storage, network calls or heavy objects.
- You only need the smallest k items, such as the 3 cheapest or 5 oldest, from a short list.
- The problem says "swap with the minimum" or "find the minimum in the unsorted part" and the list size is small.
Where to use it in a project
- Small lists on devices or scripts where writes are costly and memory is tight.
- Interview or teaching tasks that ask you to sort by repeatedly selecting the minimum.
The solution
Split the list in two parts in your mind: sorted on the left, unsorted on the right. Scan the unsorted part for the smallest item. Swap it into the first spot of the unsorted part, which then belongs to the sorted part. Repeat until the unsorted part is empty. Each round does one scan but at most one swap, so writes stay low.
Payoff: Before: hundreds of swaps with a neighbour-swapping sort. After: at most 1 swap per item, so 20 items need at most 19 swaps.
Explain it like I am 8
You have a bag of different-sized marbles. Look through the whole bag, pull out the smallest, and put it on the table. Look through the bag again, pull out the next smallest, and put it next to it. Keep going until the bag is empty.
How it works, step by step
- Split the list in your mind: a sorted part on the left (empty at first) and an unsorted part on the right.
- Scan the whole unsorted part and remember where the smallest value sits (
minIndex). - Swap that smallest value with the first item of the unsorted part. That spot is now final.
- Grow the sorted part by one, and repeat until only one item is left.
- The last item is automatically the biggest, so you can stop one pass early.
The code in four languages
PHP
<?php
// Selection sort: repeatedly pick the smallest of the unsorted part.
function selectionSort(array $a): array {
$n = count($a);
for ($i = 0; $i < $n - 1; $i++) {
$min = $i; // assume the first unsorted item is smallest
for ($j = $i + 1; $j < $n; $j++) {
if ($a[$j] < $a[$min]) {
$min = $j; // found a smaller one
}
}
if ($min !== $i) {
[$a[$i], $a[$min]] = [$a[$min], $a[$i]]; // lock the smallest into spot i
}
}
return $a;
}
echo implode(', ', selectionSort([7, 3, 9, 2, 5])); // 2, 3, 5, 7, 9JavaScript
// Selection sort: repeatedly pick the smallest of the unsorted part.
function selectionSort(input) {
const a = [...input]; // work on a copy
const n = a.length;
for (let i = 0; i < n - 1; i++) {
let min = i; // assume the first unsorted item is smallest
for (let j = i + 1; j < n; j++) {
if (a[j] < a[min]) min = j; // found a smaller one
}
if (min !== i) {
[a[i], a[min]] = [a[min], a[i]]; // lock the smallest into spot i
}
}
return a;
}
console.log(selectionSort([7, 3, 9, 2, 5]).join(', ')); // 2, 3, 5, 7, 9Java
import java.util.*;
public class Main {
// Selection sort: repeatedly pick the smallest of the unsorted part.
static int[] selectionSort(int[] input) {
int[] a = input.clone(); // work on a copy
int n = a.length;
for (int i = 0; i < n - 1; i++) {
int min = i; // assume the first unsorted item is smallest
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min]) min = j; // found a smaller one
}
if (min != i) {
int tmp = a[i]; // lock the smallest into spot i
a[i] = a[min];
a[min] = tmp;
}
}
return a;
}
public static void main(String[] args) {
int[] sorted = selectionSort(new int[]{7, 3, 9, 2, 5});
System.out.println(Arrays.toString(sorted)); // [2, 3, 5, 7, 9]
}
}Go
package main
import (
"fmt"
"slices"
)
// selectionSort: repeatedly pick the smallest of the unsorted part.
func selectionSort(input []int) []int {
a := slices.Clone(input) // work on a copy
n := len(a)
for i := 0; i < n-1; i++ {
min := i // assume the first unsorted item is smallest
for j := i + 1; j < n; j++ {
if a[j] < a[min] {
min = j // found a smaller one
}
}
if min != i {
a[i], a[min] = a[min], a[i] // lock the smallest into spot i
}
}
return a
}
func main() {
fmt.Println(selectionSort([]int{7, 3, 9, 2, 5})) // [2 3 5 7 9]
}Time: O(n²) · Extra space: O(1). It always scans the whole unsorted part, even if the list was already sorted, so there is no early finish.
Watch out for
- Swapping inside the inner loop every time a smaller value is seen. Remember the index and swap once per pass.
- Running the outer loop to the very last item. The final item is already in place after n-1 passes.
- Thinking it is fast on nearly sorted data. Unlike insertion sort, it does the same work either way.
Quick check
- After pass 1 of selection sort, what is guaranteed?
- The smallest item is in the first spot
- The whole list is sorted
- The biggest item is in the first spot
- How many swaps does selection sort make at most for n items?
- About n × n
- log n
- n - 1
- Selection sort is given a list that is already sorted. How long does it take?
- Still O(n²)
- Very fast, O(n)
- It cannot run