Sort a list with loops
Write a Python program to sort a list using loops (without sort()).
[6, 8, 2, 3, 1, 0, 5]
[0, 1, 2, 3, 5, 6, 8]
Approach
- Bubble sort: compare neighbours and swap them when they are in the wrong order; repeat.
Solution
numbers = [6, 8, 2, 3, 1, 0, 5]n = len(numbers)for i in range(n - 1): for j in range(n - 1 - i): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]print(numbers)[0, 1, 2, 3, 5, 6, 8]
Line by line
After each outer pass the largest remaining item has “bubbled” to the end.
The inner loop can stop earlier each time, because the end is already sorted.
Tuple assignment swaps the two neighbours.
Learn the concept
New to this topic? Read the lesson, then come back.