Write a C# Program To Rotate Array To the Right In a Given Pivot?
How to rotate an array by a given pivot ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodingAlgorithm
{
public static class RotateArrayRight
{
//Rotate array to the right of a given pivot
public static int[] Rotate(int[] x, int pivot)
{
if (pivot < 0 || x == null)
throw new Exception("Invalid argument");
pivot = pivot % x.Length;
//Rotate first half
x = RotateSub(x, 0, pivot - 1);
//Rotate second half
x = RotateSub(x, pivot, x.Length - 1);
//Rotate all
x = RotateSub(x, 0, x.Length - 1);
return x;
}
private static int[] RotateSub(int[] x, int start, int end)
{
while (start < end)
{
int temp = x[start];
x[start] = x[end];
x[end] = temp;
start++;
end--;
}
return x;
}
}
}
How to rotate an array by a given pivot ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodingAlgorithm
{
public static class RotateArrayRight
{
//Rotate array to the right of a given pivot
public static int[] Rotate(int[] x, int pivot)
{
if (pivot < 0 || x == null)
throw new Exception("Invalid argument");
pivot = pivot % x.Length;
//Rotate first half
x = RotateSub(x, 0, pivot - 1);
//Rotate second half
x = RotateSub(x, pivot, x.Length - 1);
//Rotate all
x = RotateSub(x, 0, x.Length - 1);
return x;
}
private static int[] RotateSub(int[] x, int start, int end)
{
while (start < end)
{
int temp = x[start];
x[start] = x[end];
x[end] = temp;
start++;
end--;
}
return x;
}
}
}
Post a Comment