In O (n) pseudo code:
def sort (src): # Create an empty array, and set pointer to its start. def dest as array[sizeof src] pto = 0 # For every possible value. for val in 0, 1, 2: # Check every position in the source. for pfrom ranges from 0 to sizeof(src): # And transfer if matching (includes update of dest pointer). if src[pfrom] is val: dest[pto] = val pto = pto + 1 # Return the new array (or transfer it back to the source if desired). return dest
This is basically iterating over the list of sources three times, adding elements if they match the required value on this pass. But he is still O (n).
The equivalent Java code would be:
class Test { public static int [] mySort (int [] src) { int [] dest = new int[src.length]; int pto = 0; for (int val = 0; val < 3; val++) for (int pfrom = 0; pfrom < src.length; pfrom++) if (src[pfrom] == val) dest[pto++] = val; return dest; } public static void main(String args[]) { int [] arr1 = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}; int [] arr2 = mySort (arr1); for (int i = 0; i < arr2.length; i++) System.out.println ("Array[" + i + "] = " + arr2[i]); } }
which outputs:
Array[0] = 0 Array[1] = 0 Array[2] = 0 Array[3] = 1 Array[4] = 1 Array[5] = 1 Array[6] = 2 Array[7] = 2 Array[8] = 2 Array[9] = 2
But seriously, if a potential employer asked me this question, I would directly say that I can answer the question if they wish, but the correct answer is simply to use Array.sort . Then, if and only if there is a problem with this method and specific data sets, you can explore a faster way.
And this faster way would almost certainly include counting, despite the requirements. You do not complicate the work of your developers with arbitrary restrictions. Requirements should indicate what is required, not how.
If you answered this question to me in this way, I would hire you locally.