Given an array with

nobjects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.

First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.Could you come up with an one-pass algorithm using only constant space?

## Analysis

Maybe we could use some sorting algorithm, but since there are only 3 possible values, we have a better approach. As mentioned by the problem, we can iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

But if we want to do it in one-loop? We can see if we have a subarray, which is sorted, and there is a new element needed to be inserted, we can set the border of the different values and insert the new value, which means that we do not need to move all elements behind this new element to give it a position. For example, during sorting, if the array is like the following:

[table]

a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], …

0, 0, 1, 2, 2, 2, 1 , 2, 0, …

[/table]

Now sub-array a[0] – a[5] is sorted. We want to add new element a[6], which is 1. The border of 0 is 1. The border of 1 is 3. The border of 2 is 6. Now we need to move all 2s one position. In fact we can only do it by setting a[2’s border]=2. Now we have a new position, which is a[1’s border], so we can let this position equals to 1. After the operation, the array becomes:

[table]

a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], …

0, 0, 1, 1, 2, 2, 2, 2, 0, …

[/table]

We can continue doing this until we meet the end of the array.

## Code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class Solution { public void sortColors(int[] A) { int zeroPosition = 0; int onePosition = 0; int twoPosition = 0; for(int i = 0; i < A.length; i++){ if (A[i] == 0){ A[twoPosition] = 2; A[onePosition] = 1; A[zeroPosition] = 0; zeroPosition++; onePosition++; twoPosition++; } else if (A[i] == 1){ A[twoPosition] = 2; A[onePosition] = 1; onePosition++; twoPosition++; } else if (A[i] == 2){ A[twoPosition] = 2; twoPosition++; } } } } |

## Complexity

The complexity is $O(n)$.