Question: Java Create and test a class RotateRight with a method rotateRight() that takes an int array and rotates the contents of the array right in

Java

Create and test a class RotateRight with a method rotateRight() that takes an int array and rotates the contents of the array right in place (that is, the input array is changed) by the number of places passed as a parameter.

The rotateRight() method header is: public static void rotateRight(int[] a, int places)

Numbers that fall off the right should cycle back to the left. For example, if the input array numbers is { 1, 3, 5, 7 } and the call of rotateRight() is rotateRight(numbers, 2) then the numbers array should contain { 5, 7, 1, 3 } after that call.

Also write or copy a display() method to print the elements in an int array, and use it in main to test rotateRight() by displaying the elements of various arrays before and after calling the method (make it clear which is before and which is after, and what you expect the result to be).

Hints:

If the length of the input array is 0 or 1 just return immediately (in that case the order of the array elements will not change).

Set places = places % a.length; If places is now 0, just return (rotating multiples of the length of the array, including rotating 0 places, does not change it).

If places is negative, set places = a.length + places; to turn it into a positive rotation. In the above numbers example, rotating right -1 positions is the same as rotating right +3.

Create a new int array b the same length as a, and in a for loop copy the elements of a, starting at 0, into the b array: b[places] = a[i]; // i is the for loop index places = (places + 1) % a.length; // this cycles back to start

At the end of this loop, run another for loop to copy all the elements in b back into a. Now as elements have been rotated.

Some possible tests: Array places result comments { 1, 3, 5, 7 } 2 { 5, 7, 1, 3 } example above { 1, 3, 5, 7 } 18 { 5, 7, 1, 3 } 18 % 4 == 2 { 1, 3, 5, 7 } -1 { 3, 5, 7, 1 } 4 + -1 == 3 { 1, 3, 5, 7 } 8 { 1, 3, 5, 7 } 8 % 4 == 0 { 1 } 2 { 1 } places is ignored

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!