归并排序

归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

 

算法描述


 

  1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
  2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置
  3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
  4. 重复步骤3直到某一指针达到序列尾
  5. 将另一序列剩下的所有元素直接复制到合并序列尾

 

代码描述


 1         List<int> Sort(List<int> lst)
 2         {
 3             int count = lst.Count;
 4 
 5             if (count == 1) return lst;
 6 
 7             int mid = count / 2;
 8 
 9             List<int> left = new List<int>();
10             List<int> right = new List<int>();
11 
12             for (int i = 0; i < mid; i++)
13             {
14                 left.Add(lst[i]);
15             }
16 
17             for (int i = mid; i < lst.Count; i++)
18             {
19                 right.Add(lst[i]);
20             }
21 
22             left = Sort(left);
23             right = Sort(right);
24 
25             return Merge(left, right);
26         }
27 
28         List<int> Merge(List<int> left, List<int> right)
29         {
30             List<int> lst = new List<int>();
31 
32             while (left.Count > 0 && right.Count > 0)
33             {
34                 if (left[0] < right[0])
35                 {
36                     lst.Add(left[0]);
37                     left.RemoveAt(0);
38                 }
39                 else
40                 {
41                     lst.Add(right[0]);
42                     right.RemoveAt(0);
43                 }
44             }
45 
46             if (left.Count > 0)
47             {
48                 lst.AddRange(left);
49             }
50             else if (right.Count > 0)
51             {
52                 lst.AddRange(right);
53             }
54 
55             return lst;
56         }    

 

posted @ 2013-12-20 17:32  徐新文  阅读(193)  评论(0编辑  收藏  举报