快速排序:
思想:主要是利用了分而治之的思想,将一个大的排序问题简化成一个一个小的问题。
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Net; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { List<int> list = new List<int>(); //插入2k个随机数到数组中 for (int j = 0; j < 2000; j++) { Thread.Sleep(1); list.Add(new Random((int)DateTime.Now.Ticks).Next(0, 100000)); } Console.WriteLine("\n第" + i + "次比较:"); Stopwatch watch = new Stopwatch(); watch.Start(); var result = list.OrderBy(single => single).ToList();//这里这个single=>single不懂 watch.Stop(); Console.WriteLine("\n系统的快速排序耗费时间:" + watch.ElapsedMilliseconds); Console.WriteLine("输出前是十个数:"+string.Join(",",result.Take(10).ToList())); watch.Start(); new QuickSortClass().QuickSort(list, 0, list.Count - 1); watch.Stop(); Console.WriteLine("\n自己的快速排序耗费时间:" + watch.ElapsedMilliseconds); Console.WriteLine("输出前是十个数:" + string.Join(",", result.Take(10).ToList()));//这里也不是很懂 } Console.ReadLine(); } //快速排序算法 } public class QuickSortClass { private int Division(List<int> list, int left, int right) { int baseNum = list[left]; while (left < right) { while (left < right && baseNum <= list[right]) right--; list[left] = list[right]; while (left < right && baseNum >= list[left]) left++; list[right] = list[left]; } list[left] = baseNum; return left; } public void QuickSort(List<int> list, int left, int right) { if (left < right) { int i = Division(list, left, right); QuickSort(list, left, i - 1); QuickSort(list, i + 1, right); } } } }
总结:
快速排序是排序算法中最快的算法了,快的程度令人发指。
http://www.cnblogs.com/huangxincheng/archive/2011/11/14/2249046.html