Classic algorithms · 10 / 22 Exercise Medium

Bubble sort (classic algorithm)

Objective

Create a Python program that sorts a list with the bubble sort algorithm and shows how it looks after each pass.

Instructions

  • Read a line with integers separated by spaces.
  • Repeat passes: in each one go through the list comparing each element with the next one (list[i] and list[i + 1], for i from 0 to len(list) - 2) and swapping them if they are in the wrong order. Count the total swaps.
  • If a pass makes no swaps, finish without showing it. Each pass that did swap is shown as Pass K: n1 n2 ....
  • At the end show Result: n1 n2 ... and, on another line, Swaps: N.
Input
5 1 4 2 8
Output
Pass 1: 1 4 2 5 8
Pass 2: 1 2 4 5 8
Result: 1 2 4 5 8
Swaps: 4

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise