logo CodeStepByStep logo


Language/Type: C# arrays loops algorithms interview

Write a method named SortThree that accepts an array of integers, all elements of which are guaranteed to be either 0, 1, or 2, and rearranges the values to be in sorted order. For example, if an array a contains {2, 0, 2, 1, 1, 0, 0, 2}, the call of SortThree should change its contents to {0, 0, 0, 1, 1, 2, 2, 2}.

This problem could be solved easily by calling an existing library sorting method, but the challenge comes from doing it as efficiently as possible. Can you do it in a single pass over the array?

You may assume that the array does not contain any element values other than 0, 1, or 2.

Method: Write a C# method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.