Right circular rotation
Here we will discuss one of the most important programming question i.e. Right circular rotation of array in c# or How to perform Right circular rotation of an array. The only thing we need to do is to shift each position one step right.If you ant to know more logical programming please check Logical Programming section on top.
How to Perform Right circular rotation of an array?
Right-Circular-Rotation-Array |
See the Above Image . It says Before Right Circular Rotation 1 3 5 7 9 11 where as after Right circular rotation 11 1 3 5 7 9.
Lets Understand the functional logic behind Right Circular Rotation.
1 3 5 7 9 11 //Swap 1 and 3
3 1 5 7 9 11 // swap 3 and 5
5 1 3 7 9 11 // swap 5 and 7
7 1 3 5 9 11 // swap 7 and 9
9 1 3 5 7 11 // swap 9 and 11
11 1 3 5 7 9 //Final Output
9 1 3 5 7 11 // swap 9 and 11
11 1 3 5 7 9 //Final Output
In the above the Index position arr[0] will swap with arr[i+1] where i is the incremented value start with 0.
Lets understand the right circular rotation in programmatic way.
class Right_Rotation
{
public static void Main()
{
int[] arr = { 1, 3, 5, 7, 9, 11 };
Right_Rotation_Method(arr);
Console.ReadKey();
}
public static void Right_Rotation_Method(int[] arr)
{
Console.WriteLine("Before Right Circular Rotation....");
foreach (var data in arr)
{
Console.Write(data + " ");
}
Console.WriteLine("");
int temp_value = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
temp_value = arr[0];
arr[0] = arr[i + 1];
arr[i + 1] = temp_value;
}
Console.WriteLine("After Right Circular Rotation....");
foreach (var item in arr)
{
Console.Write(item + " ");
}
}
}
Program logic of Right circular rotation of array in c#
temp=arr[0]
arr[0]=arr[i+1] //where i=0,1,2,3....
arr[i+1]=temp
The above logic keep on repeating till the loop ended......arr[0]=arr[i+1] //where i=0,1,2,3....
arr[i+1]=temp
Lets understand the right circular rotation in programmatic way.
Right circular rotation of array in c#
class Right_Rotation
{
public static void Main()
{
int[] arr = { 1, 3, 5, 7, 9, 11 };
Right_Rotation_Method(arr);
Console.ReadKey();
}
public static void Right_Rotation_Method(int[] arr)
{
Console.WriteLine("Before Right Circular Rotation....");
foreach (var data in arr)
{
Console.Write(data + " ");
}
Console.WriteLine("");
int temp_value = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
temp_value = arr[0];
arr[0] = arr[i + 1];
arr[i + 1] = temp_value;
}
Console.WriteLine("After Right Circular Rotation....");
foreach (var item in arr)
{
Console.Write(item + " ");
}
}
}
Output
Right-Circular-Rotation-array-Output |
No comments:
Post a Comment