Algorithms · Visualized

Selection Sort

Sorting Algorithms

Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.

Selection Sort divides the array into a sorted part (at the front) and an unsorted part (the rest). Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.

Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.

Selection Sort

Sorting

Selection Sort divides the array into a sorted part (at the front) and an unsorted part (the rest). On every pass, it scans the unsorted part to find the smallest element and swaps it into the next open slot of the sorted part.

How Selection Sort Works

  1. Assume the first element is the current minimum.
  2. Scan the rest of the array to find the actual smallest element.
  3. Swap that smallest element with the first unsorted position.
  4. Move the boundary between sorted and unsorted forward by one.
  5. Repeat until the entire array is sorted.

Selection Sort Worked Example

Input: [29, 10, 14, 37, 13]

Pass 1: smallest in [29,10,14,37,13] is 10 → swap with position 0 → [10,29,14,37,13]. Pass 2: smallest in [29,14,37,13] is 13 → swap → [10,13,14,37,29]. Pass 3: smallest in [14,37,29] is 14, already in place. Pass 4: smallest in [37,29] is 29 → swap → [10,13,14,29,37]. Sorted.

Selection SortO(n²)
Each pass finds the smallest remaining value and swaps it into place at the front.
Step 1 / 22
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Pass 0: assume arr[0] = 29 is the minimum
Python · Sorting Algorithms in Code
def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        m = i
        for j in range(i + 1, n):
            if a[j] < a[m]:
                m = j
        a[i], a[m] = a[m], a[i]
    return a

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Selection Sort Time & Space Complexity

BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceO(1) — sorts in place

When to Use Selection Sort

  • Situations where the cost of swapping is high but comparisons are cheap, since it does at most n swaps.
  • Small arrays or teaching how a 'find the minimum' strategy builds a sorted list.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.