Start free

Advanced · Sorting algorithms · 168 of 264

Bubble sort swaps

Sort the numbers with bubble sort (repeatedly swap neighbours that are in the wrong order) and count the swaps.

Input: whole numbers on one line. Output: the sorted numbers on the first line, Swaps: <count> on the second.

Examples

Input
3 2 1
Output
1 2 3
Swaps: 3
Input
1 2 3
Output
1 2 3
Swaps: 0
Input
5 1 4 2 8
Output
1 2 4 5 8
Swaps: 4

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

All the sorting algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting algorithms exercises