DSA
    beginner

    Selection Sort

    Software Engineer path · lesson 10 of 99
    O(n²)

    Up to 12 whole numbers between -99 and 99, separated by commas or spaces.

    Try:
    3827433982100123456
    Position iCurrent minimumComparingSwapping / writingFinal

    Start: each pass selects the smallest remaining value and puts it at the front.

    Code (running line highlighted)
    1. 1for i in 0 .. n-2:
    2. 2 min = i
    3. 3 for j in i+1 .. n-1:
    4. 4 if a[j] < a[min]: min = j
    5. 5 swap(a[i], a[min])
    6. 6return a
    Comparisons
    0 / 21
    Swaps
    0 / 5

    Tap any element in the diagram to inspect its state at this step.

    1 / 35

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    One pass of selection sort

    Sequence

    Order what happens in a single pass.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    How many swaps does Selection Sort perform in the worst case?

    The short version

    Imagine picking the smallest candy from a jar one at a time. Each time you pick, you scan ALL remaining candies to find the smallest, then swap it to the front.

    In more depth

    How It Works

    Selection Sort maintains two regions: sorted (left) and unsorted (right).

    Algorithm:

    1.Find the minimum element in unsorted region
    2.Swap it with the first unsorted element
    3.Move boundary one position right
    4.Repeat until fully sorted

    Key Properties

    Fewer Swaps: Only n-1 swaps total (better than Bubble Sort)
    Not Stable: May change relative order of equal elements
    In-Place: O(1) extra space

    When to reach for this

    • When swap cost is significantly higher than comparison cost
    • When memory writes are expensive (flash memory)
    • When simplicity is prioritized over efficiency

    Interview Questions

    Amazon
    Apple
    Microsoft
    Google
    Bloomberg
    Microsoft
    LinkedIn
    Uber

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required