Selection Sort in Python
Selection sort divides the list into sorted and unsorted regions and repeatedly selects the smallest remaining value.
What is Selection Sort?
Selection sort divides the list into sorted and unsorted regions and repeatedly selects the smallest remaining value.
Implement selection sort in Python and run it online.
When should you use it?
- Practice problem solving and data structures.
- Process data when every algorithm step must be explicit.
- Prepare for programming exercises, exams, and interviews.
Selection Sort in Python visualizer
O(n²)Use Play or Step to follow each comparison and data movement.
Example code
main.py
def selection_sort(values):
result = values.copy()
for start in range(len(result)):
minimum = start
for index in range(start + 1, len(result)):
if result[index] < result[minimum]:
minimum = index
result[start], result[minimum] = result[minimum], result[start]
return result
print(selection_sort([64, 25, 12, 22, 11]))
Expected output
[11, 12, 22, 25, 64]
How it works
Each pass finds the minimum value in the unsorted suffix and swaps it into place. Time complexity is O(n²), with at most O(n) swaps.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.