Skip to content

Algorithms

Selection Sort

O(n²) time · O(1) space. It is slow, but simple and predictable.

The idea, in plain English

Selection sort is like picking a sports team. You scan everyone, pick the shortest person, and put them first in line. Then you scan the rest, pick the next shortest, and repeat until everyone stands in order.

How it works

  1. 1Look through the whole unsorted part of the list and find the smallest item.
  2. 2Swap it into the next sorted spot at the front.
  3. 3Repeat for the remaining unsorted items until you finish.

When you'd use it

Use it to teach sorting, or when swaps cost a lot — it makes fewer swaps than the other simple sorts.

Common beginner mistakes

  • Swapping too early. Find the smallest item first, then make one swap per pass.
  • Re-scanning items you already sorted.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Before: 5 2 9 1 5 6
Sorted: 1 2 5 5 6 9

See it in motion

Watch it sortSelection sortO(n²) time · O(1) space. It is slow, but simple and predictable.

Ready. Press play to watch it sort.

0
Comparisons
0
Writes
0/25
Step
0.0s
Time
ComparingSwappingSorted

Not sure this is the right topic? See the learning paths → or where this leads →