Sort an Array of 0s, 1s, and 2s Using Adjacent Swaps
Given an array nums containing only the values 0, 1, and 2, sort it in ascending order using only adjacent swaps . Unlike the one-pass partitioning trick for this kind of array, solve it here with bubble sort's repeated compare-and-swap passes — the same technique works no matter how many distinct values the array holds.
Constraints
- 1 ≤ nums.length ≤ 1000
- numsi is 0, 1, or 2
Example
nums = [2, 0, 2, 1, 1, 0][0, 0, 1, 1, 2, 2]Explanation Repeated adjacent swaps move every 0 to the front and every 2 to the back.
Bubble sort a three-value array
Initial array [2, 0, 2, 1, 1, 0].
What happens in this step
[2, 0, 2, 1, 1, 0] Sorting begins with the full array unsorted; pass 1 will compare each neighbor pair left to right, just like with any other values.
Steps to visualize
- Walk the array comparing each pair of neighbors.
- Swap whenever the left value is bigger than the right value — this works the same whether the values are 0, 1, 2, or anything else.
- Repeat passes, shrinking the unsorted region each time, until a pass makes no swaps.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Initial array [2, 0, 2, 1, 1, 0].
What happens in this step
[2, 0, 2, 1, 1, 0] Sorting begins with the full array unsorted; pass 1 will compare each neighbor pair left to right, just like with any other values.
Solution
function sortZeroOneTwo(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 = [2, 0, 2, 1, 1, 0] | [0, 0, 1, 1, 2, 2] | example from the docstring |
nums = [0, 0, 0] | [0, 0, 0] | every element is the same value |
nums = [2, 2, 2] | [2, 2, 2] | every element is the maximum value |
nums = [0, 0, 1, 1, 2, 2] | [0, 0, 1, 1, 2, 2] | already sorted, no swaps needed |
nums = [2, 1, 0] | [0, 1, 2] | worst case, fully reverse sorted |
nums = [1] | [1] | smallest valid input, a single element |
nums = [1, 0, 2, 0, 1, 2] | [0, 0, 1, 1, 2, 2] | values interleaved with no existing order |