Zed-King Institute

    Python Program for Bubble Sort

    hardListsPython

    Bubble sort repeatedly swaps neighbours that are in the wrong order, so large values "bubble" to the end.

    The question

    Read a line of integers separated by spaces and sort them in ascending order using bubble sort (do not use sort() or sorted()). Print the sorted list.

    The code

    program.py

    a = list(map(int, input().split()))
    n = len(a)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
    print(a)

    Input

    4 46 8 76 48 49 17

    Output

    [4, 8, 17, 46, 48, 49, 76]

    How it works

    1. 1The outer loop makes n − 1 passes over the list.
    2. 2The inner loop compares a[j] with a[j + 1] and swaps them if the left one is bigger.
    3. 3After pass i, the last i items are already in place, so the inner loop stops earlier each time (n − 1 − i).
    4. 4a[j], a[j + 1] = a[j + 1], a[j] swaps two items without a temporary variable.

    Common mistakes

    • Letting j go up to n − 1, so a[j + 1] goes past the end of the list (IndexError).
    • Using sort() or sorted() when the question asks for bubble sort.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Lists