11.2 Selection sort¶
Selection sort uses a simple loop. On each pass, it selects the smallest element in the unsorted range and places it at the end of the sorted range.
For an array of length \(n\), selection sort proceeds as shown below.
- Initially, all elements are unsorted, so the unsorted indices span the closed interval \([0, n-1]\).
- Find the smallest element in \([0, n-1]\) and swap it with the element at index \(0\). The first element is now in its final position.
- Find the smallest element in \([1, n-1]\) and swap it with the element at index \(1\). The first two elements are now in their final positions.
- Continue in the same way. After \(n - 1\) rounds of selection and swapping, the first \(n - 1\) elements are in their final positions.
- The only remaining element must be the largest. It is already in place, so the array is sorted.
Figure 11-2 Selection sort steps
Description of Figure 11-2: Selection sort
Each pass selects the smallest element in the unsorted range and swaps it with the first element in that range, extending the sorted prefix by one.
The array to sort is nums = [4, 1, 3, 1, 5, 2]. It contains 6 elements at indices 0 through 5. The goal is to sort them in nondecreasing order.
On each pass, i points to the first element in the unsorted range, and k records the index of the minimum found there. Green marks the unsorted portion, gray cells on the left mark the sorted prefix, and a brace above marks the current unsorted range. After selecting k, swap the minimum nums[k] with the first element nums[i] of the range, extending the sorted prefix one place to the right.
Of the eleven frames, the first ten show five passes with a selection frame and a swap frame for each. Selection shows i and k after the scan, omitting individual inner-loop comparisons. The swap frame shows the resulting array with arcs above and below the positions just swapped and hides the i and k labels. The eleventh frame shows that one element remains, so a sixth pass is unnecessary.
Select the minimum, 1 at index 1
Pass 1 selection: nums = [4, 1, 3, 1, 5, 2]. After scanning the unsorted index range [0, 5], i = 0 points to the first element, 4, and k = 1 points to the minimum, 1. There are two 1s, at indices 1 and 3. The strict less-than comparison keeps the leftmost at k = 1. There is no sorted prefix yet, and no swap has occurred.
Swap indices 0 and 1
Pass 1 swap: in the unsorted index range [0, 5], swap the minimum, 1 at index 1, with the first element, 4 at index 0. Now nums = [1, 4, 3, 1, 5, 2]. The gray sorted prefix at index 0 contains [1]. The unsorted index range [1, 5] contains [4, 3, 1, 5, 2].
Select the minimum, 1 at index 3
Pass 2 selection: nums = [1, 4, 3, 1, 5, 2]. After scanning the unsorted index range [1, 5], i = 1 points to the first element, 4, and k = 3 points to the minimum, 1. The sorted prefix at index 0 contains [1]. No swap has occurred on this pass.
Swap indices 1 and 3
Pass 2 swap: in the unsorted index range [1, 5], swap the minimum, 1 at index 3, with the first element, 4 at index 1. Now nums = [1, 1, 3, 4, 5, 2]. The gray sorted prefix at indices 0 through 1 contains [1, 1]. The unsorted index range [2, 5] contains [3, 4, 5, 2].
Select the minimum, 2 at index 5
Pass 3 selection: nums = [1, 1, 3, 4, 5, 2]. After scanning the unsorted index range [2, 5], i = 2 points to the first element, 3, and k = 5 points to the minimum, 2. The sorted prefix at indices 0 through 1 contains [1, 1]. No swap has occurred on this pass.
Swap indices 2 and 5
Pass 3 swap: in the unsorted index range [2, 5], swap the minimum, 2 at index 5, with the first element, 3 at index 2. Now nums = [1, 1, 2, 4, 5, 3]. The gray sorted prefix at indices 0 through 2 contains [1, 1, 2]. The unsorted index range [3, 5] contains [4, 5, 3].
Select the minimum, 3 at index 5
Pass 4 selection: nums = [1, 1, 2, 4, 5, 3]. After scanning the unsorted index range [3, 5], i = 3 points to the first element, 4, and k = 5 points to the minimum, 3. The sorted prefix at indices 0 through 2 contains [1, 1, 2]. No swap has occurred on this pass.
Swap indices 3 and 5
Pass 4 swap: in the unsorted index range [3, 5], swap the minimum, 3 at index 5, with the first element, 4 at index 3. Now nums = [1, 1, 2, 3, 5, 4]. The gray sorted prefix at indices 0 through 3 contains [1, 1, 2, 3]. The unsorted index range [4, 5] contains [5, 4].
Select the minimum, 4 at index 5
Pass 5 selection: nums = [1, 1, 2, 3, 5, 4]. After scanning the unsorted index range [4, 5], i = 4 points to the first element, 5, and k = 5 points to the minimum, 4. The sorted prefix at indices 0 through 3 contains [1, 1, 2, 3]. No swap has occurred on this pass.
Swap indices 4 and 5
Pass 5 swap: in the unsorted index range [4, 5], swap the minimum, 4 at index 5, with the first element, 5 at index 4. Now nums = [1, 1, 2, 3, 4, 5]. The gray sorted prefix at indices 0 through 4 contains [1, 1, 2, 3, 4]. The unsorted index range [5, 5] contains [5].
Sorting complete
After five passes, nums = [1, 1, 2, 3, 4, 5]. Indices 0 through 4 form the gray sorted prefix. The green 5 at index 5 is still marked as the one-element unsorted range [5, 5], but it must be the maximum and is already in place. The caption reads “Sorting is complete (the one remaining element is already in place).” Both i and k are hidden.
In the code, \(k\) tracks the index of the smallest element in the unsorted range:
def selection_sort(nums: list[int]):
"""Selection sort"""
n = len(nums)
# Outer loop: the unsorted range is [i, n-1]
for i in range(n - 1):
# Inner loop: find the smallest element in the unsorted range
k = i
for j in range(i + 1, n):
if nums[j] < nums[k]:
k = j # Record the index of the smallest element
# Swap the smallest element with the first element of the unsorted range
nums[i], nums[k] = nums[k], nums[i]
/* Selection sort */
void selectionSort(vector<int> &nums) {
int n = nums.size();
// Outer loop: the unsorted range is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
swap(nums[i], nums[k]);
}
}
/* Selection sort */
void selectionSort(int[] nums) {
int n = nums.length;
// Outer loop: the unsorted range is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
}
}
/* Selection sort */
void SelectionSort(int[] nums) {
int n = nums.Length;
// Outer loop: the unsorted range is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
(nums[k], nums[i]) = (nums[i], nums[k]);
}
}
/* Selection sort */
func selectionSort(nums []int) {
n := len(nums)
// Outer loop: the unsorted range is [i, n-1]
for i := 0; i < n-1; i++ {
// Inner loop: find the smallest element in the unsorted range
k := i
for j := i + 1; j < n; j++ {
if nums[j] < nums[k] {
// Record the index of the smallest element
k = j
}
}
// Swap the smallest element with the first element of the unsorted range
nums[i], nums[k] = nums[k], nums[i]
}
}
/* Selection sort */
func selectionSort(nums: inout [Int]) {
// Outer loop: the unsorted range is [i, n-1]
for i in nums.indices.dropLast() {
// Inner loop: find the smallest element in the unsorted range
var k = i
for j in nums.indices.dropFirst(i + 1) {
if nums[j] < nums[k] {
k = j // Record the index of the smallest element
}
}
// Swap the smallest element with the first element of the unsorted range
nums.swapAt(i, k)
}
}
/* Selection sort */
function selectionSort(nums) {
let n = nums.length;
// Outer loop: the unsorted range is [i, n-1]
for (let i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
let k = i;
for (let j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) {
k = j; // Record the index of the smallest element
}
}
// Swap the smallest element with the first element of the unsorted range
[nums[i], nums[k]] = [nums[k], nums[i]];
}
}
/* Selection sort */
function selectionSort(nums: number[]): void {
let n = nums.length;
// Outer loop: the unsorted range is [i, n-1]
for (let i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
let k = i;
for (let j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) {
k = j; // Record the index of the smallest element
}
}
// Swap the smallest element with the first element of the unsorted range
[nums[i], nums[k]] = [nums[k], nums[i]];
}
}
/* Selection sort */
void selectionSort(List<int> nums) {
int n = nums.length;
// Outer loop: the unsorted range is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
}
}
/* Selection sort */
fn selection_sort(nums: &mut [i32]) {
if nums.is_empty() {
return;
}
let n = nums.len();
// Outer loop: the unsorted range is [i, n-1]
for i in 0..n - 1 {
// Inner loop: find the smallest element in the unsorted range
let mut k = i;
for j in i + 1..n {
if nums[j] < nums[k] {
k = j; // Record the index of the smallest element
}
}
// Swap the smallest element with the first element of the unsorted range
nums.swap(i, k);
}
}
/* Selection sort */
void selectionSort(int nums[], int n) {
// Outer loop: the unsorted range is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element in the unsorted range
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
}
}
/* Selection sort */
fun selectionSort(nums: IntArray) {
val n = nums.size
// Outer loop: the unsorted range is [i, n-1]
for (i in 0..<n - 1) {
var k = i
// Inner loop: find the smallest element in the unsorted range
for (j in i + 1..<n) {
if (nums[j] < nums[k])
k = j // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
val temp = nums[i]
nums[i] = nums[k]
nums[k] = temp
}
}
### Selection sort ###
def selection_sort(nums)
n = nums.length
# Outer loop: the unsorted range is [i, n-1]
for i in 0...(n - 1)
# Inner loop: find the smallest element in the unsorted range
k = i
for j in (i + 1)...n
if nums[j] < nums[k]
k = j # Record the index of the smallest element
end
end
# Swap the smallest element with the first element of the unsorted range
nums[i], nums[k] = nums[k], nums[i]
end
end
Visualize execution
11.2.1 Algorithm properties¶
- Time complexity: \(O(n^2)\), nonadaptive. The outer loop runs \(n - 1\) times. The inner loop runs \(n - 1\) times on the first pass and \(1\) time on the last. The counts for successive passes are \(n - 1\), \(n - 2\), \(\dots\), \(2\), and \(1\), adding up to \(\frac{n(n - 1)}{2}\).
- Space complexity: \(O(1)\), in-place. The two indices \(i\) and \(j\) use a constant amount of extra space.
- Unstable. As shown below, a swap can move
nums[i]to the right of an equal element, reversing their relative order.
Figure 11-3 Example of instability in selection sort
Description of Figure 11-3: Swapping across positions in selection sort
See how a swap in the first pass changes the relative order of two equal 4s, and distinguish this intermediate state from stability in the final sorted output.
The initial array is [4A, 4B, 3, 1, 5, 2], with indices 0 through 5. The blue 4 initially at index 0 is labeled 4A, and the purple 4 initially at index 1 is labeled 4B. A and B distinguish the equal elements in the description only. Both cells in the figure show the number 4.
Each selection sort pass finds the minimum in the unsorted range and swaps it directly with the first element of that range. Stability is judged after all passes: do equal elements in the final output retain their original relative order?
| State | Index 0 | Index 1 | Index 2 | Index 3 | Index 4 | Index 5 |
|---|---|---|---|---|---|---|
| Before the swap | 4A | 4B | 3 | 1 | 5 | 2 |
| After the first swap | 1 | 4B | 3 | 4A | 5 | 2 |
The first pass finds the minimum, 1 at index 3, in the unsorted range [0, 5] and swaps it with 4A at index 0. The 1 is fixed at index 0, and the unsorted range shrinks to [1, 5]. Moving directly from index 0 to index 3, 4A crosses 4B at index 1. This reverses the order of the two 4s after the first pass. The figure shows only this pass and omits the later ones.
The reversal shown after the first pass is only temporary. Continuing with the code's strict less-than comparison, the second pass swaps 4B at index 1 with 2 at index 5. The full sort produces [1, 2, 3, 4A, 4B, 5], restoring the original order of the two 4s. The figure shows how a swap can cross positions, but it does not establish a final reversal for this input. For a counterexample outside the figure, start with [4A, 4B, 1]. The first pass gives [1, 4B, 4A]. On the second pass, the 4s are equal, so the strict less-than test fails and no distinct positions are swapped. The final array remains [1, 4B, 4A]. This one input suffices to show that selection sort is unstable.