logo CodeStepByStep logo

nextPermutation

Language/Type: Java algorithms arrays interview

Write a method named nextPermutation that accepts an array of integers and rearranges its elements into the next permutation of that array's values in numerical order. For example, consider the array {1, 2, 3}. The permutations of this array, arranged in numerical order, are:

{1, 2, 3}
{1, 3, 2}
{2, 1, 3}
{2, 3, 1}
{3, 1, 2}
{3, 2, 1}

So if your method were called and passed the array {2, 1, 3}, you would rearrange it to {2, 3, 1}, which is the next permutation listed above. If you are passed the last permutation in numerical order, {3, 2, 1}, rearrange it into the first permutation, {1, 2, 3}.

As another example, if passed {1, 2, 7, 8, 6, 5, 4, 3}, your method should modify the array to store {1, 2, 8, 3, 4, 5, 6, 7}.

Method: Write a Java 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.