How to rotate an array

Rotate an array by number of elements


Category: Data Structure And Algorithms Tags: C#

Rotate an array - Code Files

Problem statement

   Rotate an array by number of elements. Suppose given array of size n and number of elements d (by that rotation needs to be placed).

Arr  = [1, 2, 3, 4, 5, 6, 7, 8], n = 8

If d = 2 the output shall be:

Arr = [3, 4, 5, 6, 7, 8, 1, 2]

Solution

Method 1: Simple rotation of array (one element at a time) for d times

    We would store first element in temp location and then replace 1st element by 2nd, 2rd element by 3rd and so on. In the end we will replace last element with temp. We will do the same for d times.

    static int[] RotateLeft(int[] arr, int d)
    {
        while (d > 0)
        {
            int temp = arr[0];
            for (int i = 1; i < arr.Length; i++)
            {
                arr[i - 1] = arr[i];
            }
            arr[arr.Length - 1] = temp;
            d--;
        }
        return arr;
    }

Let’s call above method and see output.

    static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        var rotatedArr = RotateLeft(arr, 2);

        Console.Write("Array after rotation: ");
        foreach (int ele in rotatedArr)
        {
            Console.Write(ele + ",");
        }
    }

Output

Array after rotation: 3,4,5,6,7,8,1,2,

Method 2: Using reversal algorithm

Reversal algorithm reverses the array three times as following:

  1. Reverse array elements [0, d-1]
  2. Reverse array elements [d, n]
  3. Reverse array elements [0, n]

Look at the code below.

    static int[] RevrseArr(int[] arr, int a, int b)
    {
        var mid = (a + b) / 2;
        for (int i = a; i <= mid; i++, b--)
        {
            int temp = arr[i];
            arr[i] = arr[b];
            arr[b] = temp;
        }
        return arr;
    }

Above code reverses array between given index, we will call this method 3 times to rotate the array.

    static int[] RotateLeftReversal(int[] arr, int d)
    {
        arr = RevrseArr(arr, 0, d - 1);
        arr = RevrseArr(arr, d, arr.Length - 1);
        return RevrseArr(arr, 0, arr.Length - 1);
    }

Let’s run this code and see output.

    static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        var rotatedArr = RotateLeftReversal(arr, 2);

        Console.Write("Array after rotation: ");
        foreach (int ele in rotatedArr)
        {
            Console.Write(ele + ",");
        }
    }

Output

Array after rotation: 3,4,5,6,7,8,1,2,


Like 0 People
Last modified on 14 May 2021
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 144
Questions: 15
Given Best Solutions: 15 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x