吃螺丝

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

先来简单说下什么是合并排序

合并排序-将一个集合分为两个或更多的子集,采用分治法,得到排序之后的合集。

昨天自己研究了下,然后写了一段代码,可运行,希望感兴趣的朋友能多提点。

 

//////我是分割线///////

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CombinAlgorithm
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] test = new int[10]{2,6,5,9,10,3,4,8,1,0};
            Divide(test,0,9);   //执行 分治 合并排序
            foreach (int item in test)
            {
                Console.Write(item.ToString()+" ");
            }
            Console.Read();
        }

        public static void Divide(int[] test,int left,int right)
        {
            if (left == right) //判断 如果只有一个元素时  不执行分治
            {
                return;
            }
            int middle = (left + right) / 2;  //设置中间点
            Divide(test,left,middle);    //递归执行  左边
            Divide(test,middle+1,right);   //递归执行  右边
            Merge(test,left,middle,right);  //合并  左右两边
        }

        public static void Merge(int[] test,int left,int middle,int right)
        {
            int tempLeftMark = left;
            int[] tempLeft = new int[middle-left+1]; //左边临时数组
            int maxLeft = middle - left + 1;

            int tempRightMark = middle + 1;
            int[] tempRight = new int[right - middle]; //右边临时数组
            int maxRight = right - middle;

            for (int i = 0; i < maxLeft; i++)
            {
                tempLeft[i] = test[tempLeftMark];
                tempLeftMark++;
            }

            for (int i = 0; i < maxRight; i++)
            {
                tempRight[i] = test[tempRightMark];
                tempRightMark++;
            }
            int iL = 0;
            int jR = 0;
            while (iL<maxLeft&&jR<maxRight)  //while 循环   把小的那个 放入test数组中  指针下移
            {
                if (tempLeft[iL] <= tempRight[jR])
                {
                    test[left] = tempLeft[iL];
                    iL++;
                }
                else
                {
                    test[left] = tempRight[jR];
                    jR++;
                }
                left++;
            }

            //把剩下的数组copy到test中
            if (iL==maxLeft)
            {
                while (jR<maxRight)
                {
                    test[left] = tempRight[jR];
                    jR++;
                    left++;
                }
            }

            if (jR==maxRight)
            {
                while (iL<maxLeft)
                {
                    test[left] = tempLeft[iL];
                    iL++;
                    left++;
                }
            }
        }
    }
}

冒泡排序的算法复杂度是N的N次方,运用合并排序 显然算法复杂度是小于冒泡排序的,为nlogn.

posted on 2011-09-23 11:56  吃螺丝  阅读(221)  评论(0编辑  收藏  举报