Implement Bubble Sort
Given an integer array nums, sort it in ascending order and return the sorted array. You must sort it using bubble sort : repeatedly walk the array comparing each pair of neighbors, swapping them whenever the left value is bigger than the right one, until a full pass makes no swaps.
Constraints
- 1 ≤ nums.length ≤ 1000
- -104 ≤ numsi ≤ 104
Example
nums = [5, 3, 8, 4, 2][2, 3, 4, 5, 8]Explanation Repeated adjacent swaps move each value toward its correct spot until the array reads [2, 3, 4, 5, 8].
In plain terms
- Bubble sort
- A sorting technique that repeatedly compares neighboring elements and swaps them when they are out of order, so the largest unsorted value "bubbles" to its final position on each pass.
Compare and swap neighbors, one pass at a time
Initial array, before any passes: [5, 3, 8, 4, 2].
What happens in this step
[5, 3, 8, 4, 2] Sorting begins with the full array unsorted; pass 1 will compare each neighbor pair left to right.
Steps to visualize
- Walk the array left to right, comparing each pair of adjacent values.
- Swap the pair whenever the left value is bigger than the right value.
- After a full pass, the largest unsorted value sits at the end — shrink the unsorted region by one.
- Repeat until a pass finishes with zero swaps.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Initial array, before any passes: [5, 3, 8, 4, 2].
What happens in this step
[5, 3, 8, 4, 2] Sorting begins with the full array unsorted; pass 1 will compare each neighbor pair left to right.
Solution
function bubbleSort(nums) {
const arr = nums.slice();
const n = arr.length;
for (let pass = 0; pass < n - 1; pass++) {
let swapped = 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;
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}- Time
- O(n^2)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [5, 3, 8, 4, 2] | [2, 3, 4, 5, 8] | example from the docstring |
nums = [1, 2, 3] | [1, 2, 3] | already sorted, no swaps needed |
nums = [5, 4, 3, 2, 1] | [1, 2, 3, 4, 5] | worst case, reverse sorted input |
nums = [7] | [7] | smallest valid input, a single element |
nums = [3, 1, 3, 2, 1] | [1, 1, 2, 3, 3] | duplicate values scattered through the array |
nums = [-2, 5, -1, 0, 3] | [-2, -1, 0, 3, 5] | negative values mixed with positive ones |
nums = [4, 4, 4] | [4, 4, 4] | every element is the same value |
nums = [2, 1] | [1, 2] | boundary case, exactly two elements out of order |