Reverse an array in C#
This post will discuss how to reverse an array in C#.
1. Using Array.Reverse()
method
To in-place reverse the order of the elements within the specified array, we can use the Array.Reverse() method. The solution works by overwriting the existing elements of the specified array without using any auxiliary array.
The following example shows how to reverse the values in an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int[] array = { 2, 4, 6, 8 }; Array.Reverse(array); Console.WriteLine(String.Join(',', array)); } } /* Output: 8,6,4,2 */ |
2. Using Enumerable.Reverse()
method
To create a reversed copy of the original array, we can use the Enumerable.Reverse() method. It just creates a new sequence with elements in the reverse order without modifying the underlying array. The following code example reverses an array using the Reverse()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 2, 4, 6, 8 }; int[] reverse = Enumerable.Reverse(array).ToArray(); Console.WriteLine(String.Join(',', reverse)); } } /* Output: 8,6,4,2 */ |
3. Custom Routine
Another solution is to create a new array of the same type and size as the input array, fill it with elements from the source array in reverse order, and then copy the new array’s contents into the source array.
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 |
using System; public static class Extensions { public static void reverse<T>(this T[] array) { int n = array.Length; T[] aux = new T[n]; for (int i = 0; i < n; i++) { aux[n - 1 - i] = array[i]; } for (int i = 0; i < n; i++) { array[i] = aux[i]; } } } public class Example { public static void Main() { int[] array = { 2, 4, 6, 8 }; array.reverse(); Console.WriteLine(String.Join(',', array)); } } /* Output: 8,6,4,2 */ |
The above implementation requires O(n) extra space for the auxiliary array. We can avoid that by modifying the array in-place, as shown below:
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 |
using System; public class Example { private static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void Main() { int[] array = { 2, 4, 6, 8 }; int n = array.Length; for (int i = 0; i < n/2; i++) { swap(array, i, n-i-1); } Console.WriteLine(String.Join(',', array)); } } /* Output: 8,6,4,2 */ |
That’s all about reversing an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)