代码改变世界

三行代码实现快速排序

2011-11-24 19:09  calm_水手  阅读(327)  评论(0编辑  收藏  举报
/// <summary>
/// 快速排序函数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
IEnumerable<T> QuickSorting<T>(IEnumerable<T> list) where T : IComparable<T>
{
if (list.Count() <= 1) return list;

var pivot
= list.First();

return QuickSorting(list.Where(x => x.CompareTo(pivot) < 0))
.Concat(list.Where(x
=> x.CompareTo(pivot) == 0))
.Concat(QuickSorting(list.Where(x
=> x.CompareTo(pivot) > 0)));

}
测试:
 static void Main(string[] args)
{
List
<int> ints = new List<int>
{
22,33,11,43,55,123,452,1,3,5,15,153,10000,532,553,22,33,11,53,11,33
};
List
<int> lists = new Program().QuickSorting<int>(ints).ToList<int>();

lists.ForEach(A
=> Console.WriteLine(A));
}

文章出自:http://www.cnblogs.com/tianmaicheng/archive/2011/08/26/2154756.html