← Back to course
Python 11-12 / Week 09 / Tuesday
2/6
Week 09 Β· Sorting

Tuesday

Selection sort in code
// Selection and insertion sort; count the work
⏱ about 30 min

Tuesday: Selection Sort in Code

Comet wraps yesterday's steps in a loop. "One pass for each place," she says, typing fast. "That is the whole sort."

Wren stops her before she runs it. "What does the evidence say? Let's print the list after every pass and check it against yesterday's cards."

Comet groans, then grins. "Fine. If the prints match the cards, I win."

Nova projects the four pass rows from Monday beside an empty output box. "How can I help?" she asks. "Watch i and smallest. They tell the whole story of each pass."

Comet passes you the keyboard. "Lead programmer, trace it with us."

selection_sort()

The outer loop picks the place i to fill. The inner loop finds the smallest item from i to the end. Then one swap puts it in place i.

This is the function you will type into sorts.py tomorrow. The copy below adds one print, so you can see each pass.

def selection_sort(nums):
    for i in range(len(nums) - 1):
        smallest = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[smallest]:
                smallest = j
        nums[i], nums[smallest] = nums[smallest], nums[i]
# selection_passes.py
# A copy of selection_sort that prints the list after each pass.


def selection_passes(nums):
    for i in range(len(nums) - 1):
        smallest = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[smallest]:
                smallest = j
        nums[i], nums[smallest] = nums[smallest], nums[i]
        print("pass", i + 1, nums)


selection_passes([42, 18, 65, 7, 30])
iPart searchedsmallest (index)SwapList after the pass
042, 18, 65, 7, 303 (value 7)places 0 and 3[7, 18, 65, 42, 30]
118, 65, 42, 301 (value 18)place 1 with itself[7, 18, 65, 42, 30]
265, 42, 304 (value 30)places 2 and 4[7, 18, 30, 42, 65]
342, 653 (value 42)place 3 with itself[7, 18, 30, 42, 65]
TRACE SELECTION_PASSES.PY
  • Read the question.
  • Tap your answer.
How many passes does it print for five numbers?
On pass 3 (i is 2), which two values swap?
Why is there no fifth pass?
pass 1 [7, 18, 65, 42, 30]
pass 2 [7, 18, 65, 42, 30]
pass 3 [7, 18, 30, 42, 65]
pass 4 [7, 18, 30, 42, 65]

It sorts words too

The < in selection_sort works on strings as well. Run this and see the order it gives. Made-up data from the FieldSim story.

# sort_kinds.py
from field_data import CATALOG


def selection_sort(nums):
    for i in range(len(nums) - 1):
        smallest = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[smallest]:
                smallest = j
        nums[i], nums[smallest] = nums[smallest], nums[i]


kinds = []
for label, kind, grams in CATALOG:
    kinds.append(kind)
selection_sort(kinds)
print(kinds[0])
print(kinds[-1])
After sorting the ten kinds, which kind comes first?
Which kind comes last?
basalt
slate
At your computer
1. Type selection_passes.py in your fieldsim folder, save it and run it. Check all four passes against the table.
2. Change one thing: sort [65, 42, 30, 18, 7] instead. Predict pass 1, then run.
3. Break it on purpose: indent the swap line four more spaces, so it sits inside the inner for loop. Run it and compare with the correct list.
4. Put the indent back and run once more.

This is the run for step 3. There is no traceback, but the list is wrong.

# indent_oops.py


def selection_oops(nums):
    for i in range(len(nums) - 1):
        smallest = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[smallest]:
                smallest = j
            nums[i], nums[smallest] = nums[smallest], nums[i]


nums = [42, 18, 65, 7, 30]
selection_oops(nums)
print(nums)
[30, 7, 18, 42, 65]
READ THE INDENT RUN
  • Read the question.
  • Tap your answer.
What kind of error is the extra indent?
How could a test catch it?
StatementTrue or false?
The inner loop finds the smallest item; the swap comes after it.?
selection_sort gives back a new sorted list.?
The same selection_sort can sort strings into A to Z order.?
Indentation decides which loop a line belongs to.?
WHY THIS EXERCISEselection_sort changes the list it is given, its swap belongs after the inner loop, and < also orders strings.

Four passes, four rows, every one checked. Tomorrow you build sorts.py and count every comparison.

← Monday