一个归并排序的例子:对一个随机点的链表进行排序 | |
分类 | 排序算法 |
---|---|
数据结构 | 数组 |
最差时间复杂度 | ![]() |
最优时间复杂度 | ![]() |
平均时间复杂度 | ![]() |
最差空间复杂度 | ![]() |
最佳算法 | 有时是 |
。
归并操作(merge),也叫归并算法,指的是将两个已经排序的序列合并成一个序列的操作。归并排序算法依赖归并操作。
[编辑]算法描述
归并操作的过程如下:
- 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
- 设定两个指针,最初位置分别为两个已经排序序列的起始位置
- 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
- 重复步骤3直到某一指针达到序列尾
- 将另一序列剩下的所有元素直接复制到合并序列尾
C#语言
public static List<int> sort(List<int> lst) { if (lst.Count <= 1) { 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; }
[编辑]
归并排序
归并排序具体工作原理如下(假设序列共有n个元素):
- 将序列每相邻两个数字进行归并操作,形成
个序列,排序后每个序列包含两个元素
- 将上述序列再次归并,形成
个序列,每个序列包含四个元素
- 重复步骤2,直到所有元素排序完毕
-
void merge_sort(int array[], unsigned int first, unsigned int last){ int mid = 0; if(first<last) { /*mid = (first+last)/2;*/ /*注意防止溢出*/ /*mid = first/2 + last/2;*/ /*mid = ((first & last) + (first ^ last) >> 1);*/ mid = ((first & last) + ((first ^ last) >> 1)); /*修正上一句优先级错误*/ merge_sort(array, first, mid); merge_sort(array, mid+1,last); merge(array,first,mid,last); }}
算法复杂度
比较操作的次数介于和
。 赋值操作的次数是
。 归并算法的空间复杂度为:Θ (n)