Java Program for Program to cyclically rotate an array by one
Last Updated :
05 Sep, 2022
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 };
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;
}
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
Please Login to comment...