Putting things in order
Sorting means putting items into a chosen order. You might arrange numbers from smallest to largest or scores from highest to lowest. Decide the rule first: there is no single “right order” for every task.
This is a next-step article. Try lists, indexing, and while loops first. Read slowly and follow the cards on paper.
Swap neighbouring cards
Write 4, 1, 3, and 2 on four cards. Compare two neighbours. If the left number is larger, swap them. Move one place right and repeat. After one trip across the row, the largest number has reached the end.
Repeat the trip. Several trips can sort the entire row. This method is called bubble sort. It is easy to demonstrate, though not the fastest method for large collections.
Sort four numbers
# language: en
let numbers = [4, 1, 3, 2]
let pass = 0
while pass < length(numbers) - 1:
let index = 0
while index < length(numbers) - 1:
if numbers[index] > numbers[index + 1]:
let saved = numbers[index]
set numbers[index] = numbers[index + 1]
set numbers[index + 1] = saved
set index = index + 1
set pass = pass + 1
for number in numbers:
say number
saved keeps the first value while the two cells swap. The inner loop makes one trip across the row. The outer loop repeats that trip three times for four items. This simple version still checks pairs that are already in order.
Predict, then run
After the first trip the cards are 1, 3, 2, 4. Is that fully sorted yet? The final output is:
1
2
3
4
Your challenge
Try [3, 1, 3, 2]. Both copies of three should remain. Then try an already sorted list. Can you explain why no swaps are needed? The code also handles an empty list without trying to read a missing cell.
A common mistake
Replacing the left cell before saving its old value loses a number. Another mistake is visiting the last index and then requesting index + 1, which would be outside the list. The - 1 in the inner condition prevents that.
