HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

A character array of arbitary length with 'R', 'B', 'W' is needed to be sorted in that order

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
neededorderarraylengthwithcharacterthatarbitarysorted

Problem

There is a char array of n length. The array can have elements only from
any order of R, B, W. You need to sort the array so that order should R,B,W
(i.e. all R will come first followed by B and then W).


Constraints: Time
complexity is O(n) and space complexity should be O(1).


Assumption:
You can assume one swap method is given with signature swap(char[]
arr, int index1, int index2)
that swaps number in unit time. Method
given to implement: public sort(char[]array);

Here is my implementation of it. A better solution from anyone is appreciated. Anyone is free to point out any mistakes.

public static void sort(char[] arr){
     int rIndex = 0, wIndex = arr.length -1;
     for (int i = 0 ; i <= wIndex;){
         if ( arr[i] == 'R' ){
             swap(arr, i , rIndex ++ );
             i ++;
         } else if (arr[i] == 'W' ){
             swap(arr, i , wIndex -- );
         }else{
            i ++;
         }
     }
}

Solution

Don't bother swapping. Just do a counting sort!

public static void sort(char[] arr) {
    // Count occurrences of each letter
    int r = 0, b = 0, w = 0;
    for (char c : arr) {
        switch (c) {
          case 'R': r++; break;
          case 'B': b++; break;
          case 'W': w++; break;
          default: throw new IllegalArgumentException();
        }
    }

    // Write out the appropriate repetitions of each letter
    int i = 0;
    while (r-- > 0) arr[i++] = 'R';
    while (b-- > 0) arr[i++] = 'B';
    while (w-- > 0) arr[i++] = 'W';
}


Not only is the code easy to understand, it's also gentle to the cache since you always proceed linearly down the array.

Code Snippets

public static void sort(char[] arr) {
    // Count occurrences of each letter
    int r = 0, b = 0, w = 0;
    for (char c : arr) {
        switch (c) {
          case 'R': r++; break;
          case 'B': b++; break;
          case 'W': w++; break;
          default: throw new IllegalArgumentException();
        }
    }

    // Write out the appropriate repetitions of each letter
    int i = 0;
    while (r-- > 0) arr[i++] = 'R';
    while (b-- > 0) arr[i++] = 'B';
    while (w-- > 0) arr[i++] = 'W';
}

Context

StackExchange Code Review Q#31944, answer score: 8

Revisions (0)

No revisions yet.