This is not a sorting problem; this is a grouping problem.
Go to the list by counting the number of red, white and blue elements. Now you know the exact structure of your solution, for example:
XXXXYYYYZZZZZZZZZZ
Where X is red, Y is white, and Z is blue.
Now create three pointers: one at the beginning of the beginning of X, one at the beginning of Y and one at the beginning of Z in A.
Move each pointer until it is the first element in its set, which is incorrect. For example, if it is A:
XYXXYYXYZZZZZZZZZZ
I
We would move the I, X-pointer to the second position (index 1), because this element is inappropriate.
If you do this for each pointer, you know that each of the three pointers indicates the absence of an element. Then go through the list. Whenever you find an item inappropriate, replace it with the appropriate pointer, i.e. If you find X in Ys, replace it with the Y pointer, and then increase that pointer (Y) until it points to something inappropriate again.
Continue until the array is sorted.
Since you iterate over once (n ops) in the list to get a structure, and then each pointer will not iterate over the list once (4 pointers → 4n), your total maximum runtime will be 5n, which is O (n).
Jason source share