Sort Colors
Given an array of integers where each integer can be 0, 1, or 2, represent three different 'colors'. Your task is to sort this array in-place such that elements of the same color are adjacent, with the colors in the order of 0, 1, and 2. The function should not return anything; instead, it should arrange the elements of the array so that it is sorted appropriately. This problem is to be solved without using the library's sort function.
[ 2, 1, 0 ]
Explanation. Simple test with only one occurrence of each number.
[ 2, 0, 2, 1, 1, 0 ]
Explanation. The array should be arranged so that all 0's are before all 1's and all 1's are before all 2's.
[ 0, 0, 1, 1, 2, 2 ]
Explanation. The input is already sorted, so it should remain unchanged.
[ 2, 2, 1, 1, 0, 0 ]
Explanation. The array elements need to be reversed from 2, 2, 1, 1, 0, 0 to 0, 0, 1, 1, 2, 2.
[ 0, 1, 1, 0, 2, 2 ]
Explanation. Mixed elements but still needs to be ordered according to the problem statement.
Follow-up: Can you come up with a one-pass algorithm using only constant extra space?
The input array will only contain the integers 0, 1, and 2. Your solution should strive for linear time complexity O(n) and constant space complexity O(1).
- Views
- 3