O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ) { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required