归并排序的C#实现

来源:互联网 发布:linux查看hadoop版本 编辑:程序博客网 时间:2024/05/16 08:45
归并操作的工作原理如下:
第一步:申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
第二步:设定两个指针,最初位置分别为两个已经排序序列的起始位置
第三步:比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
重复步骤3直到某一指针超出序列尾
将另一序列剩下的所有元素直接复制到合并序列尾
下面是C#代码
class Program    {        static void Main(string[] args)        {            //定义两个有序数组            int[] a = new int[] { 1, 4, 6, 22, 38 };            int[] b = new int[] { 6, 32, 48,64};            int[] x = merge(a, b);            foreach (var i in x)            {                Console.Write("{0}\t",i);            }            Console.ReadKey();        }        public static int[] merge(int[] a, int[] b)        {            int[] x = new int[a.Length + b.Length];            int i = 0;            int j = 0;            int k = 0;                        //当任一数组循环至结束时,结束循环            while (i < a.Length && j < b.Length)            {                //比较两个数组中的元素,谁大放在x数组中,下标指向下一位                if (a[i] < b[j])                {                    x[k++] = a[i++];                }                else                {                    x[k++] = b[j++];                }            }            //当任一数组循环至结束时,将另一数组添加至x数组的末尾            while (a.Length > i)                x[k++] = a[i++];            while (b.Length > j)                x[k++] = b[j++];                           return x;                }    }