Tuesday 19 August 2014

Sort an array of three color balls

Let us assume an array has 3 colors (Red, Green, Blue) of balls. Sort the array such that, all the red balls come first, next green and blue last.

public class RGB {
    
    static void sortArray(char arr[]){
        int red=0;
        int blue=arr.length-1;
        
        for(int i=0; i<=blue; i++){
            if(red < blue){
                if(arr[i] == 'r'){
                    char tmp = arr[i];
                    arr[i] = arr[red];
                    arr[red] = tmp;
                    red++;
                }
                else if(arr[i] == 'b'){
                    char tmp = arr[i];
                    arr[i] = arr[blue];
                    arr[blue] = tmp;
                    blue--;
                    i--;
                }
            }
        }
    }
    
    public static void main(String args[]){
        char arr[] = {'g','b','r','r','b','g','b','r'};
        
        sortArray(arr);
        for(int i=0; i<arr.length; i++)
            System.out.print(arr[i] +" ");
    }
}


Output
r r r g g b b b




Prevoius                                                 Next                                                 Home

1 comment:

  1. Do we really need this if(red < blue){ ?

    passing all testcases without it.. check this program.
    void fix( char *input)
    {
    int len=strlen(input) ;
    int R=0 , B=len-1;
    char temp;
    for(int j=0 ; j<=B ; j++)
    {
    if(input[j]=='R')
    {
    temp=input[R];
    input[R]=input[j];
    input[j]=temp;
    R++;
    }
    else if(input[j]=='B')
    {
    temp=input[B];
    input[B]=input[j];
    input[j]=temp;
    B--;
    j--;
    }
    }
    }

    ReplyDelete