Bubble sort

Sorts eight random numbers by swapping neighbours; step through and watch the list in Variables. Teaches nested loops and sorting.

Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Bubble sort example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""Sorts eight random numbers by swapping neighbours. Step through and watch the list in Variables. Teaches nested loops and sorting."""
from random import randint

numbers: list[int] = []
# Eight random numbers.
for i in range(8):
    numbers.append(randint(1, 99))
print("Before:", numbers)
n: int = len(numbers)
temp: int = 0
# Each pass moves the largest remaining number to the end.
for k in range(n - 1):
    for i in range(n - 1 - k):
        # Neighbours in the wrong order swap through a helper variable.
        if numbers[i] > numbers[i + 1]:
            temp = numbers[i]
            numbers[i] = numbers[i + 1]
            numbers[i + 1] = temp
print("After:", numbers)

Follow-up tasks

Tasks in which you change the example (with a model solution):

All examples