-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate An Array Left + Right
42 lines (40 loc) · 1.3 KB
/
Rotate An Array Left + Right
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
namespace Algorithms
{
class Program
{
// Create an algorithm that rotates the contents of an
// array to the left by one space. For example, if given
// an array with the numbers Input: {1, 2, 3, 4, 5, 6},
// the returned array should be Output: {2, 3, 4, 5, 6, 1}.
// The rotation should be done in place. A new array
// should not be created.
// Attempt to rotate contents to the right as well in a
// separate algorithm below it.
static void RotateArrayLeft(int[] input)
{
int temp = input[0];
for(int i = 0; i < input.Length - 1; i++)
{
input[i] = input[i + 1];
}
input[input.Length - 1] = temp;
}
static void RotateArrayRight(int[] input)
{
int temp = input[input.Length - 1];
for(int i = input.Length - 1; i > 0; i--)
{
input[i] = input[i - 1];
}
input[0] = temp;
}
static void Main(string[] args)
{
int[] arr = {1, 2, 3, 4, 5, 6};
RotateArrayLeft(arr);
Array.ForEach(arr, Console.WriteLine);
RotateArrayRight(arr);
Array.ForEach(arr, Console.WriteLine);
}
}
}