Java program to cyclically rotate an array by one

In this tutorial, you will learn how to cyclically rotate an array by one in Java language. Arrays are homogeneous collections of elements. Because of its vast importance and uses arrays are the most famous data structures in a programming language. Programmers use arrays in different areas because of their functionalities. So all these create a need for a programmer to learn about arrays. Not only learn to become a good programmer one should able to play with arrays and should be ready to do any task that requires arrays.

Now here our task is to rotate array by one in a cyclic manner. It is one of the basic operations on the array but in many cases, it comes shady. So, learning how to do it makes our tasks easy. You can consider the below example to know what we are going to do.

Input:  array[] = {1, 2, 3}/before rotation                    
Output: array[] = {3, 1, 2}/after rotation

Steps for Cyclically rotate an array by one in JAVA

For cyclic rotation, the last element of the array should come to index zero shifting every element right side by one index (i.e elements at first index is to be moved the second index ).

Steps to do it :

  • Take array as input.
  • Once input is taken pass the array to the method rotate where we rotate an array by one in a cyclic manner.
  • For rotating array, we will store the last element array in a temporary variable then each element is shifted to the right by one index and at last value stored in the temporary variable is copied to the array at index zero.
  • The modified array is returned to the main method and printed.
import java.util.Arrays; 

class codespeedy
{ 
static int a[] = new int[]{1, 2, 3}; 
  

public static void main(String[] args) { 

System.out.println("Input Array is"); 
System.out.println(Arrays.toString(a)); 
    
int x = a[a.length-1], i; 
for (i = a.length-1; i > 0; i--) 
  a[i] = a[i-1]; 
a[0] = x;
    
System.out.println("Rotated Array is"); 
System.out.println(Arrays.toString(a)); 

} 
} 
Output:
Input Array is
[1, 2, 3]
Rotated Array is
[3, 1, 2]

Time complexity: O(n)

Space complexity: O(1)

Also, visit:

 

Leave a Reply

Your email address will not be published. Required fields are marked *