Sort by Color

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: Using library sort function is not allowed.

Example :

Input : [0 1 2 0 1 2]
Modify array so that it becomes : [0 0 1 1 2 2]
Method:

counting sort

Solution:

Time: O(n)
Space: O(1)

public class Solution {
    public void sortColors(ArrayList<Integer> a) {
        int red = 0;
        int white = 0;
        int blue = 0;
        for (int i = 0; i < a.size(); i ++) {
            int curr = a.get(i);
            if (curr == 0) {
                red ++;
            } else if (curr == 1) {
                white ++;
            } else {
                blue ++;
            }
        }
        for (int i = 0; i < a.size(); i ++) {
            if (red > 0) {
                a.set(i, 0);
                red --;
            } else if (white > 0) {
                a.set(i, 1);
                white --;
            } else {
                a.set(i, 2);
                blue --;
            }
        }
    }
}