归并排序

Posted by 磊落 on May 11, 2020

归并排序

特点

  • 稳定排序

  • 时间复杂度:O(nlog2(n)) 递归log2(n)层,每层时间复杂度为O(n)

思想

  • 确定分界点,将给定序列中点作为分界点,划分成两个子序列 mid = (l + r) / 2

  • 递归排序左右区间 left 和 right

  • 归并两个有序数组,注意是有序数组,合二为一

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;
int q[N], tmp[N];

void merge_sort(int q[], int l, int r)
{
    if (l >= r) return;

    int mid = l + r >> 1;

    merge_sort(q, l, mid), merge_sort(q, mid + 1, r);

    int k = 0, i = l, j = mid + 1;
    while (i <= mid && j <= r)
    {
        if (q[i] <= q[j]) tmp[k++] = q[i++];
        else tmp[k++] = q[j++];
    }

    while (i <= mid) tmp[k++] = q[i++];
    while (j <= r) tmp[k++] = q[j++];

    for (i = l, j=0; i <= r; i++, j++) q[i] = tmp[j];


}

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &q[i]);

    merge_sort(q, 0, n - 1);
    
    for (int i = 0; i < n; i++) printf("%d ", q[i]);


    return 0;
}