结构上是递归的,为了解决给定的问题,算法一次或者多次递归调用自身,解决紧密相关的子问题,通常有三个步骤:
- 分解:将问题分级为若干个子问题
- 解决:对子问题进行递归求解,如果子问题足够小,则直接求解
- 合并:子问题的解还原为原问题的解
使用归并法排序:
static void Main(string[] args) { //产生随机序列 var rand = new Random(); List<int> sequence = new List<int>(); int length = 18; for (int i = 0; i < length; i++) { sequence.Add(rand.Next()%10); Console.Write("{0} ", sequence[i]); } //归并法排序 Merge_Sort(sequence, 0, length-1); //输出排序后的序列 Console.WriteLine(); for (int i = 0; i < length; i++) { Console.Write("{0} ", sequence[i]); } } static void Merge_Sort(List<int> sq, int s, int e) { if (s < e) { int q = (s + e) / 2; Merge_Sort(sq, s, q); Merge_Sort(sq, q+1, e); Merge(sq, s, q, e); } } static void Merge(List<int> sq, int s, int m, int e) { List<int> sequenceL = new List<int>(); for (int i = s; i <= m; i++) sequenceL.Add(sq[i]); List<int> sequenceR = new List<int>(); for (int i = m+1; i <= e; i++) sequenceR.Add(sq[i]); int li = 0, ri = 0; for (int k = s; k <= e; k++) { if (li >= sequenceL.Count) { sq[k] = sequenceR[ri]; ri++; continue; } if (ri >= sequenceR.Count) { sq[k] = sequenceL[li]; li++; continue; } if (sequenceL[li] < sequenceR[ri]) { sq[k] = sequenceL[li]; li++; } else { sq[k] = sequenceR[ri]; ri++; } } }