Sorting

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Select the smallest remaining value and place it at the current position.

Step 1 / 5
Problem shape
Current lesson

Selection Sort Lab

Sorting Beginner

Selection Sort

Welcome to the Selection Sort algorithm lab. Select the smallest remaining value and place it at the current position. Use it when: Use for teaching or when swaps are very expensive and n is tiny. The time complexity is O(n^2), and the space complexity is O(1). The pseudocode is: for i from 0 to n - 1 best = i for j from i + 1 to n - 1 if a[j] < a[best] best = j swap a[i], a[best] As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n^2)

Space

O(1)

Pseudocode

for i from 0 to n - 1
  best = i
  for j from i + 1 to n - 1
    if a[j] < a[best] best = j
  swap a[i], a[best]
Open deeper structure lesson
1.0x