How to rotate an array k time using C#?

CsharpServer Side ProgrammingProgramming

Given an array and number k, the problem states that we have to rotate the array k times.

If the given number is 3 then the array must be rotated 3 times.

Create a function reverse which takes the array, start and end as a parameter.

  • In the 1st step call reverse method from 0 to array length.

  • In the 2nd step call the reverse method from 0 to k-1.

  • In the 3rd step call the reverse method from k+1 to array length.

Example

 Live Demo

using System;
namespace ConsoleApplication{
   public class Arrays{
      public void ReverseArrayKTimes(int[] arr, int k){
         Reverse(arr, 0, arr.Length - 1);
         Reverse(arr, 0, k - 1);
         Reverse(arr, k, arr.Length - 1);
      }
      private void Reverse(int[] arr, int start, int end){
         while (start < end){
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
         }
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
         a.ReverseArrayKTimes(arr, 3);
         for (int i = 0; i < arr.Length; i++){
            Console.WriteLine(arr[i]);
         }
         Console.ReadLine();
      }
   }
}

Output

3 2 1 9 8 7 6 5 4
raja
Published on 27-Aug-2021 12:20:12
Advertisements