Selection Sort
Return the input sorted from smallest to largest by selecting the remaining minimum.
EXECUTION LAB
Return the input sorted from smallest to largest by selecting the remaining minimum.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): a = values.copy() i = 0 while ((i + 1) < len(a)): smallest = i j = (i + 1) while (j < len(a)): if (a[j] < a[smallest]): smallest = j j = (j + 1) if (smallest != i): a[i], a[smallest] = a[smallest], a[i] i = (i + 1) return aVisualizer
Step 1 of 905i, smallest
11j
24
32
Inspect the current state
Compare candidate 1 with minimum position 0.
Variable watch
i 0j 1smallest 0
Step explanation
Compare candidate 1 with minimum position 0.
comparisons 2reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n²) time · O(n) returned copy, O(1) auxiliary space
Worked explanation
Select the shortest unlined-up student for each new place.
Guided solution
After each pass the prefix is final. Search the unplaced suffix for its smallest value.
O(n²) time · O(n) returned copy, O(1) auxiliary auxiliary space
Examples
Worked example · {"values":[5,1,4,2],"target":0} ⇒ [1,2,4,5]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[3,3],"target":0} ⇒ [3,3]
Progressive hints
Hint 1
Select the shortest unlined-up student for each new place.Hint 2
After each pass the prefix is final. Search the unplaced suffix for its smallest value.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Swapping immediately whenever a smaller item appears wastes writes.
Interview follow-up
Why can the minimum swap disturb stability?