C# Swap Methods

You have an array or string in your C# program and want to swap the values in two separate elements so that they both are still present but in opposite locations. There is no built-in method for this purpose on most types so you have to implement a custom swap method for string characters and other types. Here we look at how you can implement swap methods in the C# programming language that operate on the string data type or an integer array type.

Implementing swap methods

First, this example shows how you can swap two characters in a string's character buffer and also how you can swap two elements in an array with elements of type Int32. The method that swaps string characters is more complex because the string type is immutable and you cannot assign characters to locations in a string directly. For the string swap method, we use the ToCharArray parameterless instance method and the new string constructor and return a new string reference.

~~~ Program that swaps characters and array elements (C#) ~~~

using System;

class Program
{
    static void Main()
    {
        //
        // Swap characters in the string.
        //
        string value1 = "Dot Net Perls";
        string swap1 = SwapCharacters(value1, 0, 1);
        Console.WriteLine(swap1);
        //
        // Swap elements in array.
        //
        int[] array1 = { 1, 2, 3, 4, 5 };
        SwapInts(array1, 0, 1);
        foreach (int element in array1)
        {
            Console.Write(element);
        }
    }

    static string SwapCharacters(string value, int position1, int position2)
    {
        //
        // Swaps characters in a string. Must copy the characters and reallocate the string.
        //
        char[] array = value.ToCharArray(); // Get characters
        char temp = array[position1]; // Get temporary copy of character
        array[position1] = array[position2]; // Assign element
        array[position2] = temp; // Assign element
        return new string(array); // Return string
    }

    static void SwapInts(int[] array, int position1, int position2)
    {
        //
        // Swaps elements in an array. Doesn't need to return a reference.
        //
        int temp = array[position1]; // Copy the first position's element
        array[position1] = array[position2]; // Assign to the second element
        array[position2] = temp; // Assign to the first element
    }
}

~~~ Output of the program ~~~

oDt Net Perls       (The first two characters were swapped.)
21345               (The first two elements were swapped.)

SwapCharacters method. The program text defines the Main entry point and two swap implementations for the string type and int[] array type. The SwapCharacters method receives three parameters, the first being a reference to a string, and the second two being the first position and the second position of the values you want to swap. The SwapCharacters method invokes the ToCharArray method, which returns the logical char[] buffer stored internally in the string. It uses a temporary variable, assigns the positions, and returns a new string.

See ToCharArray Method, Converting String to Array.

SwapInts method. The second method defined in the program text is the SwapInts method, which does not return a reference but is a void method. It receives three parameters, the first being an array reference with elements of type Int32, and the two positions you want to exchange. It also uses a temporary variable, but the int[] array is modified in-place so no reference must be returned.

Exceptions. This code will cause exceptions if you call it with invalid parameters. If you are developing a library function that will have many callers, you can validate the arguments with if-statements and then throw ArgumentNullException, ArgumentInvalidException and IndexOutOfRangeException instances. However, this negatively impacts performance in tight loops and is only necessary when many callers will exist.

XOR swap algorithm

Here we note an interesting bitwise algorithm that uses the XOR bitwise operator (^=) in the C# programming language to swap two elements. In computing history, this method was faster because it reduced the number of registers in use. However, as Wikipedia notes it is now much slower than using a normal temporary variable. The author has confirmed this in the C# language and the C programming language using GCC. In the C# language, bitwise operators are not the focus of the optimization efforts in the JIT and thus may be neglected in more aggressive optimizations during runtime.

Visit en.wikipedia.org.

Summary

Here we saw two methods written in the C# programming language targeting the .NET Framework that effectively swap characters in a string or elements in an array. These methods were tested and proven correct on the input provided. We also discussed problems with swapping algorithms such as exceptions, and also noted the XOR swap algorithm and its drawbacks in modern programming languages and optimizing compilers.

See Algorithm Content.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen