Skip to main content

Comparison Based Sorting

Selection Sort: Algorithm, Dry Run, Code & Complexity Explained

What is Selection Sort?

Selection Sort divides the array into a sorted left portion and an unsorted right portion. In each pass it finds the minimum element in the unsorted portion and swaps it to its correct position at the boundary.

Algorithm Steps

  1. Assume element at position i is the minimum
  2. Scan from i+1 to end, updating min index if a smaller element is found
  3. Swap arr[i] with arr[min_idx]
  4. Move the sorted boundary one step right
  5. Repeat for n-1 passes

Code Implementation

šŸ Python

def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_idx = i                      # assume current is min
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j              # new minimum found
        if min_idx != i:
            arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

ā˜• Java

public class SelectionSort {
    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[i];
                arr[i] = arr[minIdx];
                arr[minIdx] = temp;
            }
        }
    }
}

āš™ļø C++


#include <vector>
using namespace std;

void selectionSort(vector& arr) {
    int n = arr.size();
    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) {
            swap(arr[i], arr[minIdx]);
        }
    }
}

🟔 JavaScript

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]]; // swap
        }
    }
    return arr;
}

console.log(selectionSort([20, 10, 35, 2, 15, 30]));
// Output: [2, 10, 15, 20, 30, 35]

Dry Run — arr = [20, 10, 35, 2, 15, 30]

Current minimum
Scanning range
Sorted (final)

Pass 0 (i=0) — Scan indices 1–5

20
idx 0
10
idx 1
35
idx 2
2
idx 3 min
15
idx 4
30
idx 5

Min = 2 at index 3. Swap arr[0] ⇄ arr[3]

2
idx 0 āœ“
10
idx 1
35
idx 2
20
idx 3
15
idx 4
30
idx 5

Pass 1 (i=1) — Scan indices 2–5

2
idx 0 āœ“
10
idx 1 min
35
idx 2
20
idx 3
15
idx 4
30
idx 5

Min = 10 at index 1 — already in place, no swap needed

2
idx 0 āœ“
10
idx 1 āœ“
35
idx 2
20
idx 3
15
idx 4
30
idx 5

Pass 2 (i=2) — Scan indices 3–5

Scanning: 35 → 20 → 15 āœ“ (min at index 4) → 30. Swap arr[2] ⇄ arr[4]

2
idx 0 āœ“
10
idx 1 āœ“
15
idx 2 āœ“
20
idx 3
35
idx 4
30
idx 5

Pass 3 (i=3) — Scan indices 4–5

Min = 20 at index 3 — already in place, no swap needed

2
idx 0 āœ“
10
idx 1 āœ“
15
idx 2 āœ“
20
idx 3 āœ“
35
idx 4
30
idx 5

Pass 4 (i=4) — Scan index 5

Min = 30 at index 5. Swap arr[4] ⇄ arr[5]

2
idx 0 āœ“
10
idx 1 āœ“
15
idx 2 āœ“
20
idx 3 āœ“
30
idx 4 āœ“
35
idx 5 āœ“

šŸŽ‰ Sorted: [2, 10, 15, 20, 30, 35]

Comparisons Per Pass

Pass (i)ComparisonsSwaps
051 (20⇄2)
140 (already in place)
231 (35⇄15)
320 (already in place)
411 (35⇄30)
Total15 = n(n-1)/23 (max n-1 swaps!)

Time & Space Complexity

CaseTimeReason
BestO(n²)Always scans full unsorted portion — no early exit
AverageO(n²)Same scan regardless of order
WorstO(n²)Same scan regardless of order
SpaceO(1)In-place — only min_idx variable used

Is Selection Sort Stable?

āŒ No. Swapping a non-adjacent minimum to the front can change the relative order of equal elements. Use Insertion Sort or Merge Sort when stability is required.

Selection Sort vs Bubble Sort

FeatureSelection SortBubble Sort
Total SwapsO(n) — at most n-1O(n²) — many per pass
ComparisonsO(n²)O(n²)
Stable?āŒ Noāœ… Yes
Best caseO(n²) — no improvementO(n) — with optimization
Best forWhen swap cost is high (flash/disk)Nearly sorted data