DrawCode Algorithm Visualizer • Sorting • Easy

Selection Sort

Tags: Sorting, In-Place, Comparison, Selection

1. One-Liner

Selection Sort maintains a growing sorted prefix by repeatedly selecting the smallest remaining element and swapping it into the next slot.


2. The Problem It Solves

You want a dead-simple O() sort with at most O(n) swaps — helpful when writes are expensive compared to reads (e.g., flash).


3. The Core Idea

Pick the next smallest from the unsorted pile and place it after the sorted part — like repeatedly taking the lowest-numbered ticket from a hat.


4. How It Works (Step-by-Step)

StepWhat Happens
1.For i from 0 to n-2, treat 0..i-1 as sorted
2.Scan j = i..n-1 to find index m of the minimum value
3.Swap a[i] with a[m]
4.Increment i

5. Dry Run Example

[7, 3, 9, 1] → min at end → swap with index 0 → [1, 3, 9, 7] → next min is 3 (in place) → then swap 9 and 7 → [1, 3, 7, 9].


6. Key Properties

PropertyValue
SwapsO(n) total
StableNo — long swaps break equal-key order
In-placeYes

7. Where It Is Used

Company / SystemHow They Use It
Tiny embedded listsWhen code size matters more than asymptotics
TeachingContrasts swap count with Bubble Sort

8. Interview Tips

State clearly: always Θ() comparisons even if sorted; contrast Insertion on nearly sorted data.


9. Comparison with Other Algorithms

AlgorithmSwapsStableNotes
SelectionO(n)NoFew writes
BubbleManyYesMore swaps
InsertionO()YesGreat if almost sorted

10. Complexity

MetricValue
Time (Best)O()
Time (Average)O()
Time (Worst)O()
SpaceO(1)
Stable?No

Implementation Example (PYTHON)

def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        m = i
        for j in range(i + 1, n):
            if arr[j] < arr[m]:
                m = j
        arr[i], arr[m] = arr[m], arr[i]
    return arr

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer