Java program to reverse an array in groups of given size


An array can be reversed in groups of given size by reversing the subarrays of the required size. An example of this is given as follows.

Array = 1 2 3 4 5 6 7 8 9 10
Group size = 3
Modified array = 3 2 1 6 5 4 9 8 7 10

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
      int size = 4;
      int n = arr.length;
      System.out.print("Original array is: ");
      for (int i = 0; i < n; i++)
      System.out.print(arr[i] + " ");
      for (int i = 0; i < n; i += size) {
         int left = i;
         int right = Math.min(i + size - 1, n - 1);
         int temp;
         while (left < right) {
            temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left += 1;
            right -= 1;
         }
      }
      System.out.print("
Modified array is: ");       for (int i = 0; i < n; i++)       System.out.print(arr[i] + " ");    } }

Output

Original array is: 1 2 3 4 5 6 7 8 9 10
Modified array is: 4 3 2 1 8 7 6 5 10 9

Now let us understand the above program.

First the original array is printed. Then a for loop is used to reverse the array in groups of given size i.e 4. The code snippet that demonstrates this is given as follows.

System.out.print("Original array is: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
for (int i = 0; i < n; i += size) {
   int left = i;
   int right = Math.min(i + size - 1, n - 1);
   int temp;
   while (left < right) {
      temp = arr[left];
      arr[left] = arr[right];
      arr[right] = temp;
      left += 1;
      right -= 1;
   }
}

Then the modified array is displayed. The code snippet that demonstrates this is given as follows.

System.out.print("
Modified array is: "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements