Card 16: Sorting

Module 6: Advanced Techniques

1 The Hook

How does Netflix rank Top 10 movies? How does Amazon sort price Low-to-High?

They use Sorting Algorithms.

  • Goal: Put numbers in order (e.g. 1, 2, 3).
  • Method: Compare and Swap.

2 Worked Example: The Swap

To sort, we often need to swap two items.

# We want to swap A and B
a = 5
b = 10
# Use a Temp variable
temp = a # Save 5
a = b # a becomes 10
b = temp # b becomes 5

PREDICT

What happens to the list?

nums = [8, 2, 5]
if nums[0] > nums[1]:
  nums[0] = nums[1]
  nums[1] = 8
print(nums)

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Swap Shop

1. nums = [10, 5, 20].
2. The code tries to swap index 0 (10) and index 1 (5).
3. Fill in the missing variables to complete the swap.

> _
SILVER (FIX)

🥈 Broken Logic

This code only swaps if nums[0] < nums[1] (Less Than).
1. We want to sort Low-to-High.
2. So we should swap if index 0 is GREATER than index 1.
3. Fix the symbol from < to >.

> _
GOLD (MAKE)

🥇 Max Finder

1. Create a list vals = [10, 50, 20, 5].
2. Set highest = 0.
3. Loop through the list: for x in vals:.
4. Inside loop: if x > highest: then highest = x.
5. Print highest.

> _