Complexity and efficiency · 12 / 15 Exercise Hard

Bubble sort counting steps

Objective

Create a Python program that sorts a list with the bubble sort algorithm and counts its comparisons and swaps. It is an O(n²) algorithm: that is why in practice you use sorted(), which is O(n log n).

Instructions

  • Read a line with integers separated by spaces.
  • Make n - 1 passes (with n the size). In pass i compare the adjacent pairs from position 0 to n - 1 - i: if the left one is greater than the right one, swap them.
  • There is no early exit: all comparisons are always made. Count one comparison per pair looked at and one swap each time you exchange two values.
  • Show Sorted: a b c ..., Comparisons: x and Swaps: y.
Input
5 1 4 2 8
Output
Sorted: 1 2 4 5 8
Comparisons: 10
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