Write Python. Understand every error.

Open the editor

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

  1. Compare each pair of neighbours.
  2. Swap them if the left one is bigger.
  3. 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]

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: