Swap - A Resuable Method

During sorts, swapping elements is a common function, and this static class can be used instead of writing redundant code.  In this case, for the example code on this site, the function only swaps integer values in an integer-based array, but the idea could easily be overloaded for numerous array-like structures. 

Usage

The order of the numbers to swap is immaterial.  Simply pass it the zero-based positions of the items the code needs to swap.

CommonMethods.Swap(arrayToSort, firstNumber, second number);

Class

using System;

namespace Algorithms
{
    static class CommonMethods
    {
        public static int[] Swap(int[] arrayToUse, int itemOneIndex, int itemTwoIndex)
        {
            int tempValueHolder = arrayToUse[itemOneIndex];
            arrayToUse[itemOneIndex] = arrayToUse[itemTwoIndex];
            arrayToUse[itemTwoIndex] = tempValueHolder;
            return arrayToUse;
        }
    }
}

Popular posts from this blog

Heap Sort

Binary Search

Bucket Sort