Count swaps
Warm-up · Trace the algorithm · about 4 min
Bubble sort runs on [3, 5, 2, 4, 1]. Count the swaps it makes, first in pass 1 and then in total.
Example 1
Input:
{"values":[3,5,2,4,1]}
Output:
7
Constraints
- Answer with a whole number.
- A swap happens only when the left value is bigger.
Learn the idea first: Bubble sort, a visual lesson.
More Bubble sort problems
- State after one pass Warm-up
- Implement bubble sort with early exit Standard
- Array after k passes Standard
- How many swaps? Standard
- Spot the bug: the last pair Standard
- Count passes until sorted Challenge