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]
public class Solution {
    public void sortColors(ArrayList<Integer> nums) {
        int red=0;
        int blue=nums.size()-1;
        for(int i=0;i<nums.size();i++){
            if(nums.get(i)==0){
                int temp=nums.get(i);
                nums.set(i,nums.get(red));
                nums.set(red,temp);
                red++;
            }
            else if(i<blue && nums.get(i)==2){
                int temp=nums.get(i);
                nums.set(i,nums.get(blue));
                nums.set(blue,temp);
                blue--;
                i--;
            }
        }
    }
}

Last updated