Selection sort divides the array into a sorted part on the left and an unsorted part on the right. Each round it scans the unsorted part for the smallest value and swaps it into the next sorted slot. It always does the same amount of comparison work regardless of the input, and it makes at most n swaps, which is its one real advantage.
Example: Sort 6 numbers in ascending order.
When to use this
→When the number of writes (swaps) must be minimized — selection sort does at most n swaps
→Sorting small arrays where simplicity is preferred over speed
→Memory-constrained environments — sorts in place with O(1) extra space
Selection sort builds the sorted array one slot at a time. Each round it finds the smallest value in what is left and drops it into the next position from the left.
Space play/pause← → stepR replay+ − speed
active line highlighted
1
defselection_sort(arr):
2
n=len(arr)
3
foriinrange(n-1):
4
min_i=i
5
forjinrange(i+1,n):
6
ifarr[j]<arr[min_i]:
7
min_i=j
8
arr[i],arr[min_i]=arr[min_i],arr[i]
Quick check
How many swaps does selection sort perform in the worst case?
Which part of the array is always sorted during the run?