Skip to the content

Selection sort

Python · Unit 23: Searching and sorting

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. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Where does the inner loop start looking for the smallest one?

  4. 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. 5. Predict the output

    The counter goes up on every comparison. What does it print?

  6. 6. Multiple choice

    With 4 numbers selection sort made 6 comparisons. What if the list had 8?

  7. 7. Put the lines in order

    Build selection sort.

  8. 8. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →