Example 1
- Input
- nums = [2,0,2,1,1,0]
- Output
- [0,0,1,1,2,2]
Reordering in place groups the two 0s first, the two 1s next and the two 2s last.
Given an array nums holding only 0s, 1s and 2s, sort it in place so that all 0s come first, then all 1s, then all 2s. You must solve it without calling the built-in sort function.
Given an array nums with n objects colored red, white or blue, sort them in place so that objects of the same color are adjacent, in the order red, white, then blue.
The integers 0, 1 and 2 stand for red, white and blue. You must solve this problem without using the standard library sort function.
n == nums.length1 <= n <= 300nums[i] is 0, 1 or 2.Reordering in place groups the two 0s first, the two 1s next and the two 2s last.
The three colours each appear once, so the sorted array is [0, 1, 2].
The single value is already in order. Its position must still be processed when the two unknown-region boundaries meet.
After passing the initial 1, moving 2 to the end brings 0 into the scanning position. Re-examine it and swap it in front of the 1; skipping it would leave [1, 0, 2] unsorted.
Treat the values as three labeled buckets: 0 belongs at the front, 2 at the back, and 1 between them. Counting can rebuild those buckets after recording their sizes. A one-pass alternative grows finished buckets at both ends and classifies only the unknown middle. In [2, 0, 2, 1, 1, 0], moving the first 2 to the back brings a 0 into its position; that new value must be examined before the scanning pointer moves. Both methods change the supplied array and return no new array.
Reveal Counting Sort: intuition, complexity, and code
0s at the front and finished 2s at the back, and handle whatever the scanner points at next.[0], [1], and [2] remain unchanged; even mid == high must be processed.[2, 2, 2] produces harmless self/equal-value swaps as high decreases.[2, 0, 2, 0] sorts to [0, 0, 2, 2]; an empty middle block is valid.[0, 0, 1, 2, 2] remains ordered without relying on a special early exit.[2, 1, 0] needs the first and last values exchanged, then processes the middle 1 without a swap.[1, 2, 0] requires handling the 0 swapped into mid before advancing it.mid after swapping a 2 with high, even though the swapped-in value at mid has never been inspected.mid < high instead of mid <= high, which skips the final meeting position.When input falls into a few known buckets, partition pointers can file every value into its final region in a single pass with constant extra space.