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.

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);

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;

}

}

}

__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;

}

}

}

## Comments

## Post a Comment