Rotation of array without using extra space Algorithm

The Rotation of array without using extra space Algorithm is a method for rearranging the elements of an array to shift their positions by a given number of steps without using an additional data structure to temporarily store the elements. This algorithm is useful in situations where memory is limited or when optimizing the performance of a program. There are several ways to implement this algorithm, including using the reverse method, the juggling algorithm, and the block swap algorithm. One popular approach to the Rotation of array without using extra space Algorithm is the reverse method, which involves reversing the entire array, reversing the elements from 0 to the rotation step, and then reversing the remaining elements. To illustrate, let's say we have an array of integers [1, 2, 3, 4, 5] and we want to rotate it by 2 steps. First, we reverse the entire array to get [5, 4, 3, 2, 1]. Next, we reverse the elements from 0 to 2, resulting in [4, 5, 3, 2, 1]. Finally, we reverse the remaining elements, yielding the rotated array [4, 5, 1, 2, 3]. This method can be implemented efficiently with a loop and a swap function to exchange array elements, resulting in a time complexity of O(n) and a space complexity of O(1), as no additional memory is used for storing elements.
package Others;

import java.util.*;

/**
 * Rotation of array without using extra space
 * 
 *
 * @author Ujjawal Joshi
 * @date 2020.05.18
 *
 * Test Cases:

 	Input:
 	2 //Size of matrix
	1 2
 	3 4
 	Output:
 	3 1
 	4 2
 ------------------------------
 	Input:
 	3 //Size of matrix
	1 2 3 
	4 5 6
	7 8 9  
	Output:
	7 4 1 
	8 5 2
	9 6 3
 * 
 */

class main{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int a[][]=new int[n][n];
		
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
			{
				a[i][j]=sc.nextInt();
			}
		}
		int temp=0;

		// Rotation of array by swapping their values
		for(int i=0;i<n/2;i++)
		{	
			for(int j=i;j<n-i-1;j++)
			{	
				temp=a[i][j];
				a[i][j]=a[n-j-1][i];
				a[n-j-1][i]=a[n-i-1][n-j-1];
				a[n-i-1][n-j-1]=a[j][n-i-1];
				a[j][n-i-1]=temp;
			}
		}

		// printing of sorted array
    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
         System.out.print(a[i][j]+" ");

      }
      System.out.println();
    }
    
  }
    
    
}

LANGUAGE:

DARK MODE: