We will need a swapping operation which can be accomplished with
the routine shown below:
Swap
private void Swap<T>(T[] array, int first, int second)
{
T temp = array[first];
array[first] = array[second];
array[second] = temp;
}
Insertion Sort
public void InsertionSort<T> (T[] items) where T : IComparable
{
for (int i = 1; i < items.Length; i++)
{
int j = i;
while (j > 0 && items[j].CompareTo(items[j-1]) < 0)
{
Swap(items, j, j - 1);
j--;
}
}
return;
}
We have used generic operators so that sorting may be done with any type which satisfies T : IComparable, which is true of
numerical and string types. The examples below show the use of this sorting function with three types.
Example