Write a method named reverseChunks
that accepts two parameters, an array of integers a and an integer "chunk" size s, and reverses every s elements of a. For example, if s is 2 and array a stores {1, 2, 3, 4, 5, 6}
, a is rearranged to store {2, 1, 4, 3, 6, 5}
. With an s of 3 and the same elements {1, 2, 3, 4, 5, 6}
, array a is rearranged to store {3, 2, 1, 6, 5, 4}
. The chunks on this page are underlined for convenience.
If a's length is not evenly divisible by s, the remaining elements are untouched. For example, if s is 4 and array a stores {5, 4, 9, 2, 1, 7, 8, 6, 2, 10}
, a is rearranged to store {2, 9, 4, 5, 6, 8, 7, 1, 2, 10}
. It is also possible that s is larger than a's entire length, in which case the array is not modified at all. You may assume that s is 1 or greater (an s of 1 would not modify the array). If array a is empty, its contents should remain unchanged.
The following table shows some calls to your method and their expected results:
Array and Call |
Array Contents After Call |
int[] a1 = {20, 10, 30, 60, 50, 40};
reverseChunks(a1, 2);
|
{10, 20, 60, 30, 40, 50}
|
int[] a2 = {2, 4, 6, 8, 10, 12, 14, 16};
reverseChunks(a2, 3);
|
{6, 4, 2, 12, 10, 8, 14, 16}
|
int[] a3 = {7, 1, 3, 5, 9, 8, 2, 6, 4, 10, 0, 12};
reverseChunks(a3, 5);
|
{9, 5, 3, 1, 7, 10, 4, 6, 2, 8, 0, 12}
|
int[] a4 = {1, 2, 3, 4, 5, 6};
reverseChunks(a4, 8);
|
{1, 2, 3, 4, 5, 6}
|
int[] a5 = {};
reverseChunks(a5, 2);
|
{}
|