logo CodeStepByStep logo

sortThree

Language/Type: C++ vector loops algorithms interview
Related Links:

Write a function named sortThree that accepts a reference to a vector 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 a vector 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 function, but the challenge comes from doing it as efficiently as possible. Can you do it in a single pass over the vector?

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

Function: Write a C++ function as described, not a complete program.

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.