Simple and predictable
The work is always about n squared regardless of input. There is no fast case, which makes its cost easy to predict.
Selection sort finds the smallest remaining item and puts it at the front, then repeats on the rest. It makes the fewest swaps of any simple sort.
About 2 min of reading
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Run selection sort and count swaps.
Sort three numbers.
Before you run it, say out loud what it will print. Then open the answer.
Show the smallest first.
Before you run it, say out loud what it will print. Then open the answer.
Count one swap per spot.
Before you run it, say out loud what it will print. Then open the answer.
Print the rough cost of three.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
The work is always about n squared regardless of input. There is no fast case, which makes its cost easy to predict.
Selection sort minimizes swaps but not comparisons. When writing to memory is expensive, few swaps help; when comparing is expensive, it does not.
nums = [5, 2, 4]
print(min(nums))
The smallest is 2. Selection sort starts by putting that value at the front.
nums = [5, 2, 4]
i = nums.index(min(nums))
nums[0], nums[i] = nums[i], nums[0]
print(nums)
Swapping the smallest to the front fixes one spot. The rest is sorted the same way.
def select(a):
for i in range(len(a)):
m = i
for j in range(i + 1, len(a)):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return a
print(select([5, 2, 4]))
Each round fixes one more spot from the left. After n rounds the row is ordered.
nums = [3, 2, 1]
swaps = 0
for i in range(len(nums)):
swaps += 1
print(swaps)
At most one swap per spot. Selection sort swaps far less than bubble sort.
print(len([1, 2, 3]) ** 2)
Finding the smallest each round scans the rest, so the comparisons are still n squared.
rows = [[9, "x"], [1, "y"]]
print(rows[0])
When items are heavy, moving them is costly. Selection sort moves each item at most once.
rows = [[2, "a"], [2, "b"], [1, "c"]]
print(rows[0] == rows[1])
A swap can jump an equal item past another. Plain selection sort is not stable.
nums = [4, 1, 3, 2]
print(len(nums) - 1)
Each round scans the remaining items once. That scan, not the swap, is the work.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.