其他分享
首页 > 其他分享> > 2022.2.4 训练日记2 AcWing 107. 超快速排序

2022.2.4 训练日记2 AcWing 107. 超快速排序

作者:互联网

题目链接:超快速排序


题目分析:

0.归并排序
1.题解

题解


code:

#include <cstdio>

typedef long long LL;

using namespace std;

const int N = 500010;

int n;
LL q[N], w[N];//w为辅助数组

LL merge_sort(int l, int r)
{
    if(l == r) return 0;

    int mid = l + r >> 1;
    LL res = merge_sort(l, mid) + merge_sort(mid + 1, r);
    int i = l, j = mid + 1, k = 0;
    while(i <= mid && j <= r)
    {
        if(q[i] <= q[j]) w[k ++] = q[i ++];
        else
        {
            res += mid - i + 1;
            w[k ++] = q[j ++];
        }
    }

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

        for(i = l, j = 0; i <= r; i ++, j ++) q[i] = w[j];
        return res;
}    
int main()
{
    while(scanf("%d", &n), n)
    {
        for(int i = 0; i < n; i ++) scanf("%d", &q[i]);

        printf("%lld\n", merge_sort(0, n - 1));
    }
    return 0;
}

总结:

1.每一次交换可以减少一个逆序对。

标签:sort,int,LL,mid,merge,while,2022.2,107,AcWing
来源: https://blog.csdn.net/qq_53244181/article/details/122781889