Count Bubble Sort Swaps
Given an integer array nums, sort it using bubble sort and return the total number of adjacent swaps performed across every pass — not the sorted array itself. This count matters in practice: it tells you exactly how "out of order" the array was, and doubles as a measure of how much work the sort had to do.
Constraints
- 1 ≤ nums.length ≤ 1000
- -104 ≤ numsi ≤ 104
Example
nums = [5, 3, 8, 4, 2]7Explanation Bubble sorting [5, 3, 8, 4, 2] into [2, 3, 4, 5, 8] takes 7 adjacent swaps in total across all passes.
In plain terms
- Adjacent swap
- Swapping two neighboring elements because the left one is bigger than the right one.
Count every swap while sorting
Initial array [5, 3, 8, 4, 2], swap count = 0.
What happens in this step
[5, 3, 8, 4, 2], swaps = 0 Sorting begins with the counter at 0; every swap performed during any pass increments it by one.
Steps to visualize
- Run bubble sort as usual, comparing and swapping adjacent pairs pass by pass.
- Every time a swap happens, add one to a running counter.
- Keep going until a pass makes no swaps.
- Return the total count — the array itself does not need to be returned.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Initial array [5, 3, 8, 4, 2], swap count = 0.
What happens in this step
[5, 3, 8, 4, 2], swaps = 0 Sorting begins with the counter at 0; every swap performed during any pass increments it by one.
Solution
function countSwaps(nums) {
const arr = nums.slice();
const n = arr.length;
let swaps = 0;
for (let pass = 0; pass < n - 1; pass++) {
let swappedThisPass = false;
for (let i = 0; i < n - 1 - pass; i++) {
if (arr[i] > arr[i + 1]) {
const temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swaps++;
swappedThisPass = true;
}
}
if (!swappedThisPass) break;
}
return swaps;
}- Time
- O(n^2)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [5, 3, 8, 4, 2] | 7 | example from the docstring |
nums = [1, 2, 3, 4] | 0 | already sorted, zero swaps needed |
nums = [4, 3, 2, 1] | 6 | worst case, every pair out of order |
nums = [9] | 0 | smallest valid input, a single element |
nums = [2, 1] | 1 | boundary case, exactly one swap needed |
nums = [2, 2, 1] | 2 | duplicate values only count swaps against strictly smaller neighbors |
nums = [1, 5, 4, 3, 2] | 6 | sorted prefix followed by a reverse-sorted tail |
nums = [3, -1, 2, -5] | 5 | negative values mixed with positive ones |