Tutorial 16/20 — Advanced Logic

Python: Sorting Algorithms

Organising data using the Compare & Swap method. Low-to-high efficiency.

The Hook

How does Netflix rank Top 10 movies? How does Amazon sort price low-to-high?

They use Sorting Algorithms. Computers aren't magic—they just compare two things, and if they're in the wrong order, they SWAP them.

Algorithm Goal:

[8, 2, 5] [2, 5, 8]

Worked Example

The Temporary Swap logic. Critical for all sorting.

# Sorting: The Swap
# We want to swap nums[0] and nums[1]
nums = [10, 5, 20]
# 1. Save data to a TEMP space
temp = nums[0] # temp is 10
# 2. Overwrite the first space
nums[0] = nums[1] # nums[0] is 5
# 3. Retrieve from TEMP
nums[1] = temp # nums[1] is 10
Logic Gate

Predict Output

A list contains [8, 2, 5]. Run this logic:

if nums[0] > nums[1]:
  temp = nums[0]
  nums[0] = nums[1]
  nums[1] = temp
print(nums)
Level 43: Bronze

Swap Shop

"Finish the logic to swap the first and second items in the list."

> swap_buffer_standby
Level 44: Silver

Ascending Fix

"This code only swaps if the first item is SMALLER. Fix the symbol to sort Low-to-High."

> debugger_comparator_active
Level 45: Gold

Alpha Stream Finder

Relational Comparison Pattern

  • Loop through [10, 50, 20, 5].
  • Set highest = 0 initially.
  • If the current number is GREATER THAN highest, update it.
  • Print the highest value at the end.
> comparison_vector_online