Program for array rotation

Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.
Array

Rotation of the above array by 2 will make array

ArrayRotation1

METHOD 1 (Using temp array)

Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7
1) Store d elements in a temp array
   temp[] = [1, 2]
2) Shift rest of the arr[]
   arr[] = [3, 4, 5, 6, 7, 6, 7]
3) Store back the d elements
   arr[] = [3, 4, 5, 6, 7, 1, 2]

Time complexity : O(n)
Auxiliary Space : O(d)



METHOD 2 (Rotate one by one)



leftRotate(arr[], d, n)
start
  For i = 0 to i < d
    Left rotate all elements of arr[] by one
end

To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] …and finally temp to arr[n-1]

Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Rotate arr[] by one 2 times
We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation.

Below is the implementation of the above approach :

C++

// C++ program to rotate an array by
// d elements
#include <bits/stdc++.h>
using namespace std;
  
/*Function to left Rotate arr[] of 
  size n by 1*/
void leftRotatebyOne(int arr[], int n)
{
    int temp = arr[0], i;
    for (i = 0; i < n - 1; i++)
        arr[i] = arr[i + 1];
  
    arr[i] = temp;
}
  
/*Function to left rotate arr[] of size n by d*/
void leftRotate(int arr[], int d, int n)
{
    for (int i = 0; i < d; i++)
        leftRotatebyOne(arr, n);
}
  
/* utility function to print an array */
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
  
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function calling
    leftRotate(arr, 2, n);
    printArray(arr, n);
  
    return 0;
}

C

// C program to rotate an array by
// d elements
#include <stdio.h>
  
/* Function to left Rotate arr[] of size n by 1*/
void leftRotatebyOne(int arr[], int n);
  
/*Function to left rotate arr[] of size n by d*/
void leftRotate(int arr[], int d, int n)
{
    int i;
    for (i = 0; i < d; i++)
        leftRotatebyOne(arr, n);
}
  
void leftRotatebyOne(int arr[], int n)
{
    int temp = arr[0], i;
    for (i = 0; i < n - 1; i++)
        arr[i] = arr[i + 1];
    arr[i] = temp;
}
  
/* utility function to print an array */
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
  
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
    return 0;
}

Java

// Java program to rotate an array by 
// d elements 
  
class RotateArray {
    /*Function to left rotate arr[] of size n by d*/
    void leftRotate(int arr[], int d, int n)
    {
        for (int i = 0; i < d; i++)
            leftRotatebyOne(arr, n);
    }
  
    void leftRotatebyOne(int arr[], int n)
    {
        int i, temp;
        temp = arr[0];
        for (i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
        arr[i] = temp;
    }
  
    /* utility function to print an array */
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
  
    // Driver program to test above functions
    public static void main(String[] args)
    {
        RotateArray rotate = new RotateArray();
        int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
        rotate.leftRotate(arr, 2, 7);
        rotate.printArray(arr, 7);
    }
}
  
// This code has been contributed by Mayank Jaiswal

Python3

# Python3 program to rotate an array by 
# d elements 
# Function to left rotate arr[] of size n by d*/
def leftRotate(arr, d, n):
    for i in range(d):
        leftRotatebyOne(arr, n)
  
# Function to left Rotate arr[] of size n by 1*/ 
def leftRotatebyOne(arr, n):
    temp = arr[0]
    for i in range(n-1):
        arr[i] = arr[i + 1]
    arr[n-1] = temp
          
  
# utility function to print an array */
def printArray(arr, size):
    for i in range(size):
        print ("% d"% arr[i], end =" ")
  
   
# Driver program to test above functions */
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)
  
# This code is contributed by Shreyanshi Arun

C#

// C# program for array rotation
using System;
  
class GFG {
    /* Function to left rotate arr[]
    of size n by d*/
    static void leftRotate(int[] arr, int d,
                           int n)
    {
        for (int i = 0; i < d; i++)
            leftRotatebyOne(arr, n);
    }
  
    static void leftRotatebyOne(int[] arr, int n)
    {
        int i, temp = arr[0];
        for (i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
  
        arr[i] = temp;
    }
  
    /* utility function to print an array */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        leftRotate(arr, 2, 7);
        printArray(arr, 7);
    }
}
  
// This code is contributed by Sam007


Output :

3 4 5 6 7 1 2 

Time complexity : O(n * d)
Auxiliary Space : O(1)



METHOD 3 (A Juggling Algorithm)
This is an extension of method 2. Instead of moving one by one, divide the array in different sets
where number of sets is equal to GCD of n and d and move the elements within sets.
If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.

Here is an example for n =12 and d = 3. GCD is 3 and

Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

a) Elements are first moved in first set – (See below 
   diagram for this movement)

ArrayRotation

          arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}

b)    Then in second set.
          arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}

c)    Finally in third set.
          arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}

Below is the implementation of the above approach :

C++

// C++ program to rotate an array by
// d elements
#include <bits/stdc++.h>
using namespace std;
  
/*Fuction to get gcd of a and b*/
int gcd(int a, int b)
{
    if (b == 0)
        return a;
  
    else
        return gcd(b, a % b);
}
  
/*Function to left rotate arr[] of siz n by d*/
void leftRotate(int arr[], int d, int n)
{
    for (int i = 0; i < gcd(d, n); i++) {
        /* move i-th values of blocks */
        int temp = arr[i];
        int j = i;
  
        while (1) {
            int k = j + d;
            if (k >= n)
                k = k - n;
  
            if (k == i)
                break;
  
            arr[j] = arr[k];
            j = k;
        }
        arr[j] = temp;
    }
}
  
// Function to print an array
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
  
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function calling
    leftRotate(arr, 2, n);
    printArray(arr, n);
  
    return 0;
}

C

// C program to rotate an array by 
// d elements 
#include <stdio.h>
  
/* function to print an array */
void printArray(int arr[], int size);
  
/*Fuction to get gcd of a and b*/
int gcd(int a, int b);
  
/*Function to left rotate arr[] of siz n by d*/
void leftRotate(int arr[], int d, int n)
{
    int i, j, k, temp;
    for (i = 0; i < gcd(d, n); i++) {
        /* move i-th values of blocks */
        temp = arr[i];
        j = i;
        while (1) {
            k = j + d;
            if (k >= n)
                k = k - n;
            if (k == i)
                break;
            arr[j] = arr[k];
            j = k;
        }
        arr[j] = temp;
    }
}
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
  
/*Fuction to get gcd of a and b*/
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}
  
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
    getchar();
    return 0;
}

Java

// Java program to rotate an array by 
// d elements 
class RotateArray {
    /*Function to left rotate arr[] of siz n by d*/
    void leftRotate(int arr[], int d, int n)
    {
        int i, j, k, temp;
        for (i = 0; i < gcd(d, n); i++) {
            /* move i-th values of blocks */
            temp = arr[i];
            j = i;
            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }
  
    /*UTILITY FUNCTIONS*/
  
    /* function to print an array */
    void printArray(int arr[], int size)
    {
        int i;
        for (i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }
  
    /*Fuction to get gcd of a and b*/
    int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
  
    // Driver program to test above functions
    public static void main(String[] args)
    {
        RotateArray rotate = new RotateArray();
        int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
        rotate.leftRotate(arr, 2, 7);
        rotate.printArray(arr, 7);
    }
}
  
// This code has been contributed by Mayank Jaiswal

Python3

# Python3 program to rotate an array by 
# d elements 
# Function to left rotate arr[] of size n by d
def leftRotate(arr, d, n):
    for i in range(gcd(d, n)):
          
        # move i-th values of blocks 
        temp = arr[i]
        j = i
        while 1:
            k = j + d
            if k >= n:
                k = k - n
            if k == i:
                break
            arr[j] = arr[k]
            j = k
        arr[j] = temp
  
# UTILITY FUNCTIONS
# function to print an array 
def printArray(arr, size):
    for i in range(size):
        print ("% d" % arr[i], end =" ")
   
# Fuction to get gcd of a and b
def gcd(a, b):
    if b == 0:
        return a;
    else:
        return gcd(b, a % b)
   
# Driver program to test above functions 
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)
  
# This code is contributed by Shreyanshi Arun

C#

// C# program for array rotation
using System;
  
class GFG {
    /* Function to left rotate arr[] 
    of size n by d*/
    static void leftRotate(int[] arr, int d,
                           int n)
    {
        int i, j, k, temp;
        for (i = 0; i < gcd(d, n); i++) {
            /* move i-th values of blocks */
            temp = arr[i];
            j = i;
            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }
  
    /*UTILITY FUNCTIONS*/
    /* Function to print an array */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }
  
    /* Fuction to get gcd of a and b*/
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        leftRotate(arr, 2, 7);
        printArray(arr, 7);
    }
}
  
// This code is contributed by Sam007


Output :

3 4 5 6 7 1 2 

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

METHOD 4 (In-Place Rotation)
In this solution, the array is rotated in-place by computing the new index of the current value.

Algorithm:
1. Iterate over array
2. Find the new index of the current value with the formula:
newIndex = (currentIndex – (no_of_rotation % array_length) + array_length) % array_length
3. Swap currentIndex value with newIndex value.
Here is an example for n = 3.
Let arr[] be {0, 1, 2, 3, 4, 5, 6, 7}. The values of array are taken as their index number to make the algorithm more readable and simple to understand.

Current array:
Current Index Number -> Value
0                    -> 0
1                    -> 1
2                    -> 2
3                    -> 3
4                    -> 4
5                    -> 5
6                    -> 6
7                    -> 7

Iterate Over the array. Start with 0 index. 
Find its new index using the formula:
newIndex = (currentIndex - (no_of_rotation % array_length) + array_length) % array_length
Example:
(0 - (3 % 8) + 8) % 8 = 5

So the new indexes would be:
(0 - (3 % 8) + 8) % 8 = 5
(1 - (3 % 8) + 8) % 8 = 6
(2 - (3 % 8) + 8) % 8 = 7
(3 - (3 % 8) + 8) % 8 = 0
(4 - (3 % 8) + 8) % 8 = 1
(5 - (3 % 8) + 8) % 8 = 2
(6 - (3 % 8) + 8) % 8 = 3
(7 - (3 % 8) + 8) % 8 = 4

New array:
Current Index Number -> New Value
0                    -> 5
1                    -> 6
2                    -> 7
3                    -> 0
4                    -> 1
5                    -> 2
6                    -> 3
7                    -> 4

Below is the implementation of the above approach:

Java

// Java Program to rotate an array in-place
import java.util.Arrays;
  
public class ArrayRotate {
  
    // main method
    public static void main(String[] args)
    {
        int[] array = { 1, 2, 3, 4, 5, 6, 7 };
        rotate(array, 2);
  
        print(array);
    }
  
    // rotate method
    private static void rotate(int[] array, int n)
    {
        int currIndex = 0, newIndex = 0,
            backupVal = array[currIndex], newVal = array[currIndex];
        int i = 0, arrLen = array.length;
        while (i < arrLen) {
            currIndex = newIndex;
  
            // compute the new index for current value
            newIndex = (arrLen - (n % arrLen) + currIndex) % arrLen;
  
            // take backup of new index value
            backupVal = array[newIndex];
  
            // assign the value to the new index
            array[newIndex] = newVal;
  
            newVal = backupVal;
            i++;
        }
    }
  
    // method to print the array
    private static void print(int[] array)
    {
        Arrays.stream(array).forEach(a -> System.out.print(a + " "));
    }
}
  
// This code is contributed by Shantanoo Sinha
// & siddharth.india51088@gmail.com

C#

// C# Program to rotate an array in-place 
using System;
  
    
class ArrayRotate { 
    
    // main method 
    public static void Main() 
    
        int[] array = { 1, 2, 3, 4, 5, 6, 7 }; 
        rotate(array, 2); 
    
        print(array); 
    
    
    // rotate method 
    static void rotate(int[] array, int n) 
    
        int currIndex = 0, newIndex = 0, 
            backupVal = array[currIndex], newVal = array[currIndex]; 
        int i = 0, arrLen = array.Length; 
        while (i < arrLen) { 
            currIndex = newIndex; 
    
            // compute the new index for current value 
            newIndex = (arrLen - (n % arrLen) + currIndex) % arrLen; 
    
            // take backup of new index value 
            backupVal = array[newIndex]; 
    
            // assign the value to the new index 
            array[newIndex] = newVal; 
    
            newVal = backupVal; 
            i++; 
        
    
    
    // method to print the array 
     static void print(int[] array) 
    
        for(int i=0;i<array.Length;i++) Console.Write(array[i]+" ");
    
    
// This code is contributed by Subhadeep


Output :

3 4 5 6 7 1 2 

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

Please see following posts for other methods of array rotation:
Block swap algorithm for array rotation
Reversal algorithm for array rotation

Please write comments if you find any bug in above programs/algorithms.



My Personal Notes arrow_drop_up