Python programs · Lists
Python program for bubble sort
Bubble sort repeatedly compares neighbouring numbers and swaps them when they are in the wrong order.
Approach
- Compare each pair of neighbours.
- Swap them if the left one is bigger.
- After each pass the largest remaining number has moved to the end, so repeat with one fewer comparison.
The program
numbers = list(map(int, input().split())) 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)
Sample run
Input
64 34 25 12 22 11 90
Output
[11, 12, 22, 25, 34, 64, 90]
How the code works
The inner loop stops at n - 1 - i because the last i numbers are already in their final places. The swap numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] uses Python's simultaneous assignment. Bubble sort is slow for large lists, taking about n² steps, but it is an excellent way to learn how loops and comparisons work. In real programs use sorted().
Try changing it
- Sort from largest to smallest by changing the comparison.
- Stop early when a pass makes no swaps.
Common mistakes
- Running the inner loop to
n - 1every time, which still works but repeats needless comparisons. - Comparing
numbers[j]withnumbers[j + 1]whenjcan reach the last position, which gives an IndexError.