Selection sort

Picking the smallest, over and over · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Selection sort

Selection sort splits the array into a sorted part, on the left, and an unsorted part, on the right. Each round it finds the smallest element of the unsorted part and swaps it with that part's first element. So after the 1st round the smallest of all is at index 0, after the 2nd the second smallest at 1, and so on. After n − 1 rounds, the array is sorted.

To trace selection sort by hand, you mark the sorted part and each round find the smallest of the rest. With [4, 1, 3, 2]: round 1, the smallest is 1, swapped with 4: [1, 4, 3, 2]. Round 2, the smallest of the rest is 2, swapped with 4: [1, 2, 3, 4]. Round 3, the smallest of the rest is 3, already in place. Done.

Selection sort always does O(n²) comparisons. The 1st round looks at n − 1 elements, the 2nd n − 2, and so on down to 1: in total, about n² / 2. And it isn't adaptive: even if the array is already sorted, it has to walk the whole rest each round to confirm which is the minimum. In memory it's O(1): it sorts in place with 2 indexes.

Selection sort has one clear advantage: it makes very few swaps, at most n − 1, one per round. That can matter if moving an element is very expensive, for example writing to memory that wears out. But it loses at almost everything else: it's always O(n²), isn't stable and doesn't use existing order. Insertion sort, also O(n²), is usually better.

Selection sort is written with 2 nested loops. The outer one walks positions i from 0 to n − 2: it's the sorted part's edge. The inner one walks from i + 1 to the end finding the index k of the smallest. When the inner one ends, nums[i] and nums[k] are swapped. It only uses the variables i, j and k: O(1) memory.

Stable sort

Selection sort isn't stable: the swap can send an element far, ahead of an equal one. For example, in [5a, 5b, 1], the 1st round swaps 5a with 1: [1, 5b, 5a]. The 2 fives changed their relative order. That's why it's no good for sorting by several criteria in a row.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Picking the smallest, over and over