Swapping Two Elements in an Array

Problem:

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

Solution:

public static void SwapElementsInArray<T>(T[] theArray, int index1, int index2)
{
    if (theArray.Length > 0)
    {
        if (index1 >= theArray.Length || index2 >= theArray.Length || index1 < 0 || index2 < 0)
        {
            Console.WriteLine("index passed in to this method is out of bounds.");
        }
        else
        {
            T tempHolder = theArray[index1];
            theArray[index1] = theArray[index2];
            theArray[index2] = tempHolder;
        }
    }
    else
    {
        Console.WriteLine("Nothing to reverse");
    }
}

There is no specific method in the .NET Framework that allows you to swap only two specific elements within an array. The SwapElementsInArray mehtod presented in this recipe allows for only two specified elements on an array.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s