/// <summary> /// 归并排序。 /// </summary> public static class MergedSorter { public static IEnumerable<int> Sort(IEnumerable<int> ary) { if (ary.Count() == 1) return ary; IEnumerable<int> lhalf = Sort(ary.Take(ary.Count() / 2)); IEnumerable<int> rhalf = Sort(ary.Skip(ary.Count() / 2).Take(ary.Count() - ary.Count() / 2)); return Merge(lhalf, rhalf); } private static int[] Merge(IEnumerable<int> lhalf, IEnumerable<int> rhalf) { int[] destAry = new int[lhalf.Count() + rhalf.Count()]; int i = 0, j = 0, k = 0; //对比两个数组的元素。 while (i < lhalf.Count() && j < rhalf.Count()) { if (lhalf.ElementAt(i) < rhalf.ElementAt(j)) destAry[k++] = lhalf.ElementAt(i++); else destAry[k++] = rhalf.ElementAt(j++); } //填充剩余的一个已排好序的数组。 while (i < lhalf.Count()) { destAry[k++] = lhalf.ElementAt(i++); } while (j < rhalf.Count()) { destAry[k++] = rhalf.ElementAt(j++); } return destAry; } } }
上面是归并排序实现的方法,下面是调用方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArraySortTest { using ArraySort; class Program { static void Main(string[] args) { //int[] ary = { 4, 1, 3, 2, 16, 9, 10, 14, 8 }; int[] ary = { 100, 38,45,78 ,123}; foreach (int i in MergedSorter.Sort(ary)) { Console.WriteLine(i.ToString()); } Console.ReadKey(); } } }