Home > Backend Development > C#.Net Tutorial > How to rotate an array k times using C#?

How to rotate an array k times using C#?

WBOY
Release: 2023-09-12 14:49:09
forward
551 people have browsed it

如何使用 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();
      }
   }
}
Copy after login

Output

3 2 1 9 8 7 6 5 4
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template