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.
Note:
You are not suppose to use the library's sort function for this problem.
class Solution {
void swap(int A[], int i, int j)
{
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!A || n == 0)
return;
int redPos;
int whitePos;
int bluePos;
redPos = whitePos = 0;
bluePos = n-1;
while (whitePos <= bluePos)
{
if (A[whitePos] == 0)
{
swap(A, whitePos, redPos);
redPos++;
whitePos++;
}
else if (A[whitePos] == 2)
{
swap(A, whitePos, bluePos);
bluePos--;
}
else
{
whitePos++;
}
}
}
};