RedCapeFlyingCat wants a class photo of all the penguins in Data Structures, lined up from shortest to tallest. The penguins refuse to walk far, so they only ever swap with the penguin next to them. RedCapeFlyingCat wants to know how much work this will take.
You are given an array of integers . Find:
for p = 1 .. N-1:
for i = 1 .. N-p:
if A[i] > A[i+1]:
swap(A[i], A[i+1]) // this counts as one swap
Bubble sort puts an array in non-decreasing order by comparing neighbouring elements.
The sample explanation lists every swap.
There must be no trailing space at the end of Line 1.
Line 1: For example, has two larger elements before it ( and ). has none, because the before it is equal, not larger.
Line 2: Bubble sort performs swaps. Only the steps that swap are listed. The two s are never swapped.
| Pass | Swap | Array after the swap | Swaps so far |
|---|---|---|---|
| Start | |||
| and | |||
| and | |||
| and | |||
| and | |||
| and | |||
| and |