Reverse an Array In-Place
Question: Write a function to reverse an array in-place in C#.
Answer: Since arrays have direct access via the [] operator it's simple enough to iterate through the array elements and perform a swap. The key things to remember are: (1) you only need to iterate over half of the array; and (2) it's best to write this as a generic function since we make the function more useful.
Note that arrays are reference types in C# so it doesn't matter if you pass the array in by reference or by value, the outcome will be the same if the array is not initially null.
Here's the C# code:
static void Main()
{
var arr = new byte[] {0x04, 0x01, 0x02, 0x06, 0x00};
ReverseArray(arr);
foreach(var element in arr)
Console.WriteLine( element );
}
public static void ReverseArray<T>(T[] a)
{
int n = a.Length;
for (int i = 0; i < n/2; i++)
{
T t = a[n-i-1];
a[n-i-1] = a[i];
a[i] = t;
}
}
13 May 2008 Damien Wintour 0 comments







