DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 9.1 Swapping Two Elements in an Array

Problem

You want an efficient method to swap two elements that exist within a single array.

Solution

Use a temporary object to hold one of the items being swapped:

public static void SwapElementsInArray(object[] theArray, int index1, int index2)
{
    object tempHolder = theArray[index1];
    theArray[index1] = theArray[index2];
    theArray[index2] = tempHolder;
}

You can make this method strongly typed by setting theArray parameter type to a specific type. The following overload of the SwapElementsInArray method has been modified to accept an array of integers. This fix will prevent any costly boxing operations in the code that actually swaps the two elements:

public static void SwapElementsInArray(int[] theArray, int index1, int index2)
{
    int tempHolder = theArray[index1];
    theArray[index1] = theArray[index2];
    theArray[index2] = tempHolder;
}

Discussion

There is no specific method in the .NET Framework that allows only two specific elements to be swapped 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 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 reversed elements
Element 1 = 2
Element 2 = 3
Element 3 = 4
Element 4 = 1
    [ Team LiB ] Previous Section Next Section