
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Reversing an Array Quickly
|
283
Discussion
There is no specific method in the .NET Framework that allows you to swap only
two specific elements within an array. The
SwapElementsInArray method presented in
this recipe allows for only two specified elements of an array (specified in the
index1
and index2 arguments to this method).
The following code uses the
SwapElementsInArray<T> method to swap the zeroth and
fourth elements in an array of integers:
public static void TestSwapArrayElements( )
{
int[] someArray = new int[5] {1,2,3,4,5};
for (int counter = 0; counter < someArray.Length; counter++)
{
Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
SwapElementsInArray(someArray, 0, 4);
for (int counter = 0; counter < someArray.Length; counter++)
{
Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
}
This code produces the following output:
Element 0 = 1 ← The original array
Element 1 = 2
Element 2 = 3
Element 3 = 4
Element 4 = 5
Element 0 = 5 ← The array with elements swapped
Element 1 = 2
Element 2 = 3
Element 3 = 4
Element 4 = 1
5.2 Reversing an Array Quickly
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}; ...