reverse an array in csharp

To reverse an array in C#, you can either create a new array with reversed elements or you can reverse the elements in place, without creating a new array.

For in-place array reversal, you can use the following algorithm:

main.cs
public void ReverseArray(int[] arr) 
{
    int start = 0;
    int end = arr.Length - 1;

    while (start < end) 
    {
        // Swap elements arr[start] and arr[end]
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        // Move start and end towards the center
        start++;
        end--;
    }
}
346 chars
18 lines

Here, we initialize two pointers, start and end, at the beginning and end of the array respectively. Then, we swap the elements at these positions and move both pointers towards the center of the array until they meet in the middle.

To reverse an array in C# using a new array, you can use the Array.Reverse method:

main.cs
int[] arr = { 1, 2, 3, 4, 5 };
int[] reversed = (int[])arr.Clone();
Array.Reverse(reversed);

foreach (int i in reversed) 
{
    Console.Write(i + " ");
}

// Output: 5 4 3 2 1
177 chars
11 lines

Here, we create a copy of the original array using the Clone method, and then we call the Reverse method of the Array class to reverse the elements. Finally, we print out the reversed elements using a foreach loop. Note that the original array is not modified by this operation.

gistlibby LogSnag