Skip to content

Instantly share code, notes, and snippets.

@margusmartsepp
Created July 27, 2011 04:01
Show Gist options
  • Save margusmartsepp/1108647 to your computer and use it in GitHub Desktop.
Save margusmartsepp/1108647 to your computer and use it in GitHub Desktop.
insertion sort
/// <summary>
/// Method sorts a list ascendingly using insertion sort algorithm.
/// </summary>
/// <typeparam name="T"> Non null class, that implements comparable interface.
/// </typeparam>
/// <param name="data">List of T type elements, to be sorted ascendingly.</param>
/// <exception cref="System.NullReferenceException">
/// If any element in the list is 'null'. (Other then first one)
/// </exception>
/// <exception cref="System.NotSupportedException">
/// If list is readonly.
/// </exception>
public static void insertionSort<T>(IList<T> data) where T : IComparable<T>
{
int i, j;
for (i = 1; i < data.Count; i++)
{
T temp = data[i];
j = i;
while ((j > 0) && (temp.CompareTo(data[j - 1]) < 0))
{
data[j] = data[j - 1];
j--;
}
data[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment