插入排序法是一种适用于少量元素的排序,其时间复杂度为O(n^2)。
以下是使用插入排序算法进行排序的泛型版本:
/**********************************************
* 类 名 称: InsertionSort
*
* 命名空间: DreamDays.Core.Algorithms
*
* 作 者: DreamDays
*
* 说 明: 按照插入排序法对集合进行排序
*
* 时 间:2013年04月14日
*********************************************/
using System;
using System.Collections.Generic;
namespace DreamDays.Core.Algorithms
{
public static class InsertionSort
{
/// <summary>
/// 使用插入排序法对集合进行升序排列
/// </summary>
/// <typeparam name="T">元素类型,需要实现IComparable<typeparamref name="T"/>接口</typeparam>
/// <param name="list">需要排序的集合</param>
/// <returns>排序后的集合</returns>
public static IList<T> Sort<T>(IList<T> list) where T:IComparable<T>
{
T temp;
int j;
for (int i = 1; i < list.Count; i++)
{
temp = list[i];
j = i - 1;
while (j >= 0 && list[j].CompareTo(temp)>0)
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = temp;
}
return list;
}
/// <summary>
/// 使用插入排序法对集合按照传入的Comparison<typeparamref name="T"/> 比较规则进行排序
/// </summary>
/// <typeparam name="T">元素类型</typeparam>
/// <param name="list">需要排序的集合</param>
/// <param name="comparison">泛型委托,表示自定义的比较规则</param>
/// <returns>排序后的集合</returns>
public static IList<T> Sort<T>(IList<T> list, Comparison<T> comparison)
{
T temp;
int j;
for (int i = 1; i < list.Count; i++)
{
temp = list[i];
j = i - 1;
while (j >= 0 && comparison(list[j],temp) > 0)
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = temp;
}
return list;
}
}
}