Pocket Gems Interview Question

In place color sort

Interview Answers

Anonymous

Oct 13, 2016

// Sort colors // Sorting order : R < G < B public class ColorSorting { public static void main(String args[]) { Color [] objs = new Color[5]; objs[0] = new Color('r'); objs[1] = new Color('g'); objs[2] = new Color('b'); objs[3] = new Color('b'); objs[4] = new Color('r'); sortColors(objs); } public static void sortColors(Color [] c) { int lastIndex =0; Color temp = null; // Sort Red for (int i=0; i < c.length; i++) { if (c[i].c == 'r') { if (lastIndex == i) { lastIndex++; } else { // Swap Red temp = c[i]; c[i] = c[lastIndex]; c[lastIndex] = temp; lastIndex++; } } } // Sort Green and Blue for (int i = lastIndex; i < c.length; i++) { if (c[i].c == 'g') { if (lastIndex == i) { lastIndex++; } else { // Swap Green and Blue temp = c[i]; c[i] = c[lastIndex]; c[lastIndex] = temp; lastIndex++; } } } // Print Color array for (int i = 0; i < c.length; i++) { System.out.print(c[i].c + " "); } } } class Color { char c; public Color(char c) { this.c = c; } }

Anonymous

Oct 25, 2016

You could just count occurrences of each color, this uses 2 additional int variables though.