歸併排序

歸併排序(Merge sort,臺灣譯做:合併排序)是創建在歸併操做上的一種有效的排序算法。該算法是採用分治法(Divide and Conquer)的一個很是典型的應用。算法

 

算法描述ide


 

  1. 申請空間,使其大小爲兩個已經排序序列之和,該空間用來存放合併後的序列
  2. 設定兩個指針,最初位置分別爲兩個已經排序序列的起始位置
  3. 比較兩個指針所指向的元素,選擇相對小的元素放入到合併空間,並移動指針到下一位置
  4. 重複步驟3直到某一指針達到序列尾
  5. 將另外一序列剩下的全部元素直接複製到合併序列尾

 

代碼描述spa


 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         }    
相關文章
相關標籤/搜索