Program to cyclically rotate an array by one

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}

Following are steps.
1) Store last element in a variable say x.
2) Shift all elements one position ahead.
3) Replace first element of array with x.

C

#include <stdio.h>

void rotate(int arr[], int n)
{
   int x = arr[n-1], i;
   for (i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
   arr[0] = x;
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr)/sizeof(arr[0]);

    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    rotate(arr, n);

    printf("\nRotated array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

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));
    }
}


Output:
Given array is
1 2 3 4 5
Rotated array is
5 1 2 3 4

Time Complexity: O(n)
Auxiliary Space: O(1)

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.