排序算法--归并排序

基本思想:

1.将两个已经排序的序列合并成一个序列的操作。

2.申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列。

3.设定两个指针,最初位置分别为两个已经排序序列的起始位置。

4.比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置。

5.重复步骤4知道某一指针达到序列尾。

6.将另一序列剩下的所有元素直接复制到合并序列尾。

算法复杂度:

比较操作的次数介于(nlogn)/2和nlogn-n+1。

赋值操作的次数是(2nlogn).

空间复杂度:Θ (n)

具体实现:

 public static List<int> sort(List<int> lst)
        {
                return lst;
            }
            int mid = lst.Count / 2;
            List<int> left = new List<int>();//定义左侧List
            List<int> right = new List<int>();//定义右侧List
 
            //以下兩個循環把lst分為左右兩個List
            for (int i = 0; i < mid; i++)
            {
                left.Add(lst[i]);
            }
            for (int j = mid; j < lst.Count; j++)
            {
                right.Add(lst[j]);
            }
            left = sort(left);
            right = sort(right);
            return merge(left, right);
        }
        /// <summary>
        /// 合併兩個已經排好序的List
        /// </summary>
        /// <param name="left">左側List</param>
        /// <param name="right">右側List</param>
        /// <returns></returns>
        static List<int> merge(List<int> left, List<int> right)
        {
            List<int> temp = new List<int>();
            while (left.Count > 0 && right.Count > 0)
            {
                if (left[0] <= right[0])
                {
                    temp.Add(left[0]);
                    left.RemoveAt(0);
                }
                else
                {
                    temp.Add(right[0]);
                    right.RemoveAt(0);
                }
            }
            if (left.Count > 0)
            {
                for (int i = 0; i < left.Count; i++)
                {
                    temp.Add(left[i]);
                }
            }
            if (right.Count > 0)
            {
                for (int i = 0; i < right.Count; i++)
                {
                    temp.Add(right[i]);
                }
            }
            return temp;
        }

 

posted @ 2014-03-19 19:43  fang_beny  阅读(265)  评论(0编辑  收藏  举报