Rocket wants the computer to sort the IDs. He writes a loop to find the smallest. Then he gets stuck.
"How do I make two items trade places?" he asks. "If I copy one over the other, I lose it!"
Raven picks up a cup in each hand. "What do you notice when I trade these?"
"You have to move both at the same time," Rocket says.
Nova hums. "Here is a hint. Python can do both moves in one line."
a = 4 b = 9 a, b = b, a print(a, b)
Output: 9 4
The right side is worked out first, using the old values. Then both new values are stored at once.
This sort has a loop inside a loop. The outer loop picks the spot to fill. The inner loop finds the smallest card for it.
def selection_sort(items):
n = len(items)
for i in range(n - 1):
smallest = i
for j in range(i + 1, n):
if items[j] < items[smallest]:
smallest = j
items[i], items[smallest] = items[smallest], items[i]
print(items)
return items
selection_sort([7, 3, 9, 1, 5]) Output: [1, 3, 9, 7, 5] [1, 3, 9, 7, 5] [1, 3, 5, 7, 9] [1, 3, 5, 7, 9]
def selection_sort(items):
n = len(items)
for i in range(n - 1):
smallest = i
for j in range(i + 1, n):
if items[j] < items[smallest]:
smallest = j
items[i], items[smallest] = items[smallest], items[i]
print(items)
return items
selection_sort([6, 2, 8, 4]) | Statement | True or false? |
|---|---|
| The last line printed is [2, 4, 6, 8]. | ? |
| The inner loop does the swapping. | ? |
| The outer loop runs n - 1 times. | ? |
| a, b = b, a uses the old values on the right side. | ? |
Super work! You read a loop inside a loop. Tomorrow we let Python sort for us.