歸併排序(Merge sort,臺灣譯做:合併排序)是創建在歸併操做上的一種有效的排序算法。該算法是採用分治法(Divide and Conquer)的一個很是典型的應用。算法
算法描述ide
代碼描述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 }