C# program to rotate array to a given pivot
To rotate an array to a given pivot in C#, you can use array slicing and concatenation operations. Here's an example program that rotates an array to a given pivot:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
int pivot = 3;
RotateArray(numbers, pivot);
Console.WriteLine("Array after rotation:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
public static void RotateArray(int[] arr, int pivot) {
int n = arr.Length;
// Rotate the array to the right
ReverseArray(arr, 0, n - 1);
ReverseArray(arr, 0, pivot - 1);
ReverseArray(arr, pivot, n - 1);
}
public static void ReverseArray(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
In this program, we have an array of integers called numbers and a pivot index indicating the desired rotation point. We use the RotateArray method to rotate the array to the given pivot. The method performs three steps: reverse the entire array, reverse the subarray from the beginning up to the pivot index, and reverse the subarray from the pivot index to the end.
The program outputs the array after rotation:
Array after rotation:
4 5 6 7 1 2 3
In this case, the original array is { 1, 2, 3, 4, 5, 6, 7 }, and the pivot index is 3. After the rotation, the array is rotated to the right by three positions, resulting in { 4, 5, 6, 7, 1, 2, 3 }.