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.
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(); } } }
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!