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.
PREDICT
What happens to the list?
if nums[0] > nums[1]:
nums[0] = nums[1]
nums[1] = 8
print(nums)
Interactive Editor
🥉 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.
🥈 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 >.
🥇 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.