logo CodeStepByStep logo

sortThree

Language/Type: JavaScript arrays loops algorithms interview

Write a function 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 function, 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.

Function: Write a JavaScript 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.