Home  >  Article  >  Backend Development  >  How to rotate an array k times using C#?

How to rotate an array k times using C#?

WBOY
WBOYforward
2023-09-12 14:49:09507browse

如何使用 C# 将数组旋转 k 次?

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

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

Create a function reverse that takes an array, starting position, and ending position as parameters.

  • In the first step, the reverse method is called from 0 to the length of the array.

  • In the second step, the reverse method is called from 0 to k-1.

  • In the third step, the reverse method is called from k 1 to the array length.

Example

Demonstration

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

The above is the detailed content of How to rotate an array k times using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What is unboxing in C#?Next article:What is unboxing in C#?