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 - 1passes (withnthe size). In passicompare the adjacent pairs from position0ton - 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: xandSwaps: y.
5 1 4 2 8
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