9.2. Quickly Reversing an Array
Problem
You want an efficient method to reverse the order of elements within an array.
Solution
You can use the static
Reverse
method, as in this snippet of code:
int[] someArray = new int[5] {1,2,3,4,5}; Array.Reverse(someArray);
or you can write your own reversal method:
public static void DoReversal(int[] theArray) { int tempHolder = 0; if (theArray.Length > 0) { for (int counter = 0; counter < (theArray.Length / 2); counter++) { tempHolder = theArray[counter]; theArray[counter] = theArray[theArray.Length - counter - 1]; theArray[theArray.Length - counter - 1] = tempHolder; } } else { Console.WriteLine("Nothing to reverse"); } }
While there is more code to write, the benefit of the
DoReversal
method is that it is about twice as
fast as the Array.Reverse
method. In addition, you
can tailor the DoReversal
method to a specific
situation. For example, the DoReversal
method
accepts a value type array (int
), whereas the
Array.Reverse
method accepts only a reference type
(System.Array
). This means that a boxing operation
will occur for the int
value types. The
DoReversal
method removes any boxing operations.
Discussion
The following TestArrayReversal
method creates a
test array of five integers and displays the elements in their
initial order. Next, the DoReversal
method is
called to reverse the elements in the array. After this method
returns, the array is then displayed a second time as a reversed
array:
public unsafe static void TestArrayReversal( ) { ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.