Skip to the code
cf.
+10 XP

#184 Count Leaderboard Swaps

easy

A leaderboard animation sorts scores from lowest to highest by bubble sort: it walks the list again and again, and each time two neighbors are in the wrong order (the left one is bigger), it swaps them with a little slide effect.

Write countBubbleSwaps(scores) that returns how many swaps that bubble sort makes before the list is sorted ascending. Equal neighbors are never swapped.

Example 1

Input: scores = [5,1,4,2,8]
Output: 4

Pass 1 swaps 5 three times; pass 2 swaps 4 and 2. That is 4 swaps.

Example 2

Input: scores = [1,2,3]
Output: 0

Already sorted: no swaps.

Constraints

  • 0 <= scores.length <= 1000
  • 0 <= scores[i] <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).