归并排序

本文介绍了一种常用的排序算法——归并排序的实现方法,并通过C#代码详细展示了递归拆分与合并的过程。该实现首先将数组递归地分为两半,分别进行排序,然后合并两个已排序的部分。
  /// <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();
        }
    }
}

 

转载于:https://www.cnblogs.com/chengliangkaka/p/3489303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值