https://www.acwing.com/activity/content/introduction/11/
知识点对应的题目为:https://www.acwing.com/problem/content/789/
归并排序与快速排序有相似的地方,主要的区别在于,归并排序先对子序列进行排序,然后合并。具体来说,步骤为:
第3步合并时最关键的一步,主要实现的方法为双指针:
时间复杂度为
O
(
n
log
n
)
O(n\log n)
O(nlogn),这是因为双指针每做一次递归需要遍历n个数据;而归并数组不断拆分原数组为原来的一半,执行
log
n
\log n
logn次之后就结束:
#include <iostream> using namespace std; const int N = 1e5 + 10; int q[N]; int n; int temp[N]; void mergeSort(int q[], int l, int r){ if (l >= r) return; int mid = (l + r) / 2; mergeSort(q,l, mid); mergeSort(q,mid + 1, r); int left = l; int right = mid + 1; int k = 0; while (left <= mid && right <= r) if (q[left] < q[right]) temp[k++] = q[left++]; else temp[k++] = q[right++]; while (right <= r) temp[k++] = q[right++]; while (left <= mid) temp[k++] = q[left++]; for (int i = l, j = 0; i <= r; i++, j++) q[i] = temp[j]; } int main(){ scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d",&q[i]); mergeSort(q,0,n-1); for (int i = 0; i < n; i++) printf("%d ",q[i]); }