Selection sort
Python · Unit 23: Searching and sorting
- Full plan
- Python
- 8 exercises
Selection sort is what you do with cards in your hand: you look for the smallest of the ones left and put it at the front.
The first step is finding where the smallest one is. You keep the position, not the value, because later you have to move it.
ns = [5, 2, 9, 1]
m = 0
for i in range(1, len(ns)):
if ns[i] < ns[m]:
m = i
print("smallest is at", m)Prints
smallest is at 3
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
Where does the inner loop start looking for the smallest one?
4. Find the bug
This version swaps using an extra variable. It should print [1, 3, 4], but the 4 disappears and the 1 shows up twice. Which line has the error?
5. Predict the output
The counter goes up on every comparison. What does it print?
6. Multiple choice
With 4 numbers selection sort made 6 comparisons. What if the list had 8?
7. Put the lines in order
Build selection sort.
8. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.