C# Program to rotate an array by k position

In this article, we will discuss how to write a C# program to rotate an array by k position.

Understanding Array Rotation:

Array rotation involves shifting the elements of an array to the right or left by a specified number of positions. Here, we want to rotate an array to the right, focusing on a pivot element.

Example 1: Simple Rotation using Reverse

using System;

class ArrayRotation
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5 };
        int rotationPositions = 2;

        RotateArray(array, rotationPositions);

        Console.WriteLine("Rotated Array: [" + string.Join(", ", array) + "]");
    }

    static void RotateArray(int[] arr, int rotationPositions)
    {
        int n = arr.Length;

        // Ensure the rotation count is within array bounds
        int pivot = rotationPositions % n;

        // Step 1: Reverse the entire array
        Array.Reverse(arr);

        // Step 2: Reverse the elements before the pivot
        Array.Reverse(arr, 0, pivot);

        // Step 3: Reverse the elements after the pivot
        Array.Reverse(arr, pivot, n - pivot);
    }
}

Result:

Rotated Array: [4, 5, 1, 2, 3]

Code Explanation:

This example rotates the array using the Reverse method. First, the entire array is reversed, and then the elements before and after the pivot are separately reversed.

Example 2 – Brute Force Approach to rotate an array by k position:

Imagine an array [1, 2, 3, 4, 5] and a rotation of 2 positions. The result should be [4, 5, 1, 2, 3]. The elements shift to the right, and those beyond the array’s boundary reappear on the left side.

using System;

class ArrayRotation
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5 };
        int k = 2;

        RotateArrayBruteForce(array, k);

        Console.WriteLine("Rotated Array: [" + string.Join(", ", array) + "]");
    }

    static void RotateArrayBruteForce(int[] arr, int k)
    {
        int n = arr.Length;

        // Perform rotation k times
        for (int i = 0; i < k; i++)
        {
            int temp = arr[n - 1];

            for (int j = n - 1; j > 0; j--)
                arr[j] = arr[j - 1];

            arr[0] = temp;
        }
    }
}

Result:

Rotated Array: [4, 5, 1, 2, 3]

The above C# code example demonstrates a brute force approach to rotate an array to the right by k positions. Here’s a brief description of the code:

  1. Input:
    • The program initializes an array of integers (array) and specifies the number of positions to rotate (k).
  2. Brute Force Rotation:
    • The RotateArrayBruteForce method is responsible for the brute force rotation.
    • It uses two nested loops:
      • The outer loop runs for k iterations, representing the number of positions to rotate.
      • The inner loop shifts each element one position to the right, effectively rotating the array.
  3. Output:
    • The rotated array is displayed using Console.WriteLine after the rotation is complete.
  4. Time Complexity:
    • The brute force approach has a time complexity of O(n*k), where n is the length of the array. This is because, for each rotation position, it iterates through the entire array.
  5. Example:
    • In this array [1, 2, 3, 4, 5] and a rotation of 2 positions, the output will be [4, 5, 1, 2, 3]

Example 3 – Rotate an array by k positions using C# Collections:

using System;
using System.Collections.Generic;

class ArrayRotation
{
    static void Main()
    {
        List<int> array = new List<int> { 1, 2, 3, 4, 5 };
        int k = 2;

        RotateArrayUsingCollections(array, k);

        Console.WriteLine("Rotated Array: [" + string.Join(", ", array) + "]");
    }

    static void RotateArrayUsingCollections(List<int> arr, int k)
    {
        int n = arr.Count;

        // Use C# List method to rotate
        arr.InsertRange(0, arr.GetRange(n - k, k));
        arr.RemoveRange(n, k);
    }
}

Result:

Rotated Array: [4, 5, 1, 2, 3]

Recommended Articles:

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments