easy

Count Bubble Sort Swaps

Sort with bubble sort and return the total number of adjacent swaps performed.

1. Define the problem

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

Inputnums = [5, 3, 8, 4, 2]
Output7

Explanation Bubble sorting [5, 3, 8, 4, 2] into [2, 3, 4, 5, 8] takes 7 adjacent swaps in total across all passes.

2. Know the words first

In plain terms

Adjacent swap
Swapping two neighboring elements because the left one is bigger than the right one.
3. Visualize the solution

Count every swap while sorting

Count every swap while sorting
Statusstart

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.
Step 1 of 4

Steps to visualize

  1. Run bubble sort as usual, comparing and swapping adjacent pairs pass by pass.
  2. Every time a swap happens, add one to a running counter.
  3. Keep going until a pass makes no swaps.
  4. Return the total count — the array itself does not need to be returned.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Count every swap while sorting
Statusstart

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.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
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)
6. Test cases

Test cases

InputExpectedCovers
nums = [5, 3, 8, 4, 2]7example from the docstring
nums = [1, 2, 3, 4]0already sorted, zero swaps needed
nums = [4, 3, 2, 1]6worst case, every pair out of order
nums = [9]0smallest valid input, a single element
nums = [2, 1]1boundary case, exactly one swap needed
nums = [2, 2, 1]2duplicate values only count swaps against strictly smaller neighbors
nums = [1, 5, 4, 3, 2]6sorted prefix followed by a reverse-sorted tail
nums = [3, -1, 2, -5]5negative values mixed with positive ones