Open In App

Java Program for Program to cyclically rotate an array by one

Last Updated : 05 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, cyclically rotate the array clockwise by one. Examples:

Input:  arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}

Java




import java.util.Arrays;
 
public class Test
{
    static int arr[] = new int[]{1, 2, 3, 4, 5};
     
    // Method for rotation
    static void rotate()
    {
       int x = arr[arr.length-1], i;
       for (i = arr.length-1; i > 0; i--)
          arr[i] = arr[i-1];
       arr[0] = x;
    }
     
    /* Driver program */
    public static void main(String[] args)
    {
        System.out.println("Given Array is");
        System.out.println(Arrays.toString(arr));
         
        rotate();
         
        System.out.println("Rotated Array is");
        System.out.println(Arrays.toString(arr));
    }
}


Time complexity: O(n) as using a for loop

Please refer complete article on Program to cyclically rotate an array by one for more details!


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads