# [LeetCode] Sort Colors (Java)

Given an array with n objects 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.

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.

## Complexity

The complexity is $O(n)$.