leetcode Questions 99: Sort Colors

Sort Colors

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.
You are not suppose to use the library's sort function for this problem.

This is a relative easy problem.
The goal is to rearrange the array, where 0s are in the 1st part of the array, 1s in the middle, and 2s are in the    last. So, we can just scan the whole array, when meet 0, put it in the front, when meet 2, put it in the last, and leave 1 alone thus in the middle. 0 and 2's positions are stored and modified each time a swap is performed.
Details see the code.

class Solution {

    void swap(int A[], int i, int j){
        int tmp = A[i];
    void sortColors(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int red=0;
        int blue=n-1;
        while (A[red]==0){red++;}
        while (A[blue]==2){blue--;}
        int i=red;
        while (i<=blue){
            if (A[i]==0 && i>red) {swap(A,i,red);red++;continue;}
            if (A[i]==2) {swap(A,i,blue);blue--;continue;}


  1. This comment has been removed by the author.

  2. Hey, I think the line 15 in your code above should be modified something like this,
    line 15: while(red<A.length && A[red]==0) red++;
    Because, if A=[0], the index will be out of the array's boundary. And the same logic also apply for line 16.