跳到正文

休闲·娱乐

一种基于分块的排序方法

jodio9约 4 分钟
原文

这是 2026年2月25日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年2月23日
收录
2026年2月25日
更新
2026年8月27日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

由于自己觉得太水投了休闲·娱乐。

原讨论

本蒟蒻从归并排序中获得了启发,其实我们不需要将序列一分为二,可以像普通分块一样将长度为 N 的待排序序列分为 N\sqrt N 块,然后递归分别排序。当递归序列长度为 1 时退出。

时间复杂度

由于我什么都不会证,口胡一个 O(NN)O(N\sqrt N) 的时间复杂度,因为似乎只有第一次递归需要 O(NN)O(N\sqrt N) 的时间复杂度,后面的每层递归操作次数之和都不会超过 NNN\sqrt N.

空间复杂度

代码对于每次递归都开了长度为 N\sqrt N 的数组,但是并没有 MLE. 尝试证明一下。首先这个空间复杂度肯定和递归深度有关。用最简单的方法,找经过一次分块递归操作后序列长度为 1 的最小自然数,这个数是 2. 经过两次分块递归操作后序列长度为 1 的最小自然数就是 2 的平方,即 4,经过 3 次操作长度为 1 的最小自然数就是 4 的平方 16. 因此对于长度为 2x2^x 的序列分块递归深度为 logxlogx, 推广到任意长度,递归深度为 loglogNloglogN, 空间复杂度 O(NloglogN)O(\sqrt NloglogN).

提交记录

代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define il inline
#define re register
#define enter putchar_unlocked('\n')
int tmp[100005],minn,mini,n,a[100005];
void merge(int l,int r){
    if(l>=r)return;
    int t=sqrt(r-l+1),cnt=0;
    int L[2005],R[2005],point[2005];
    for(re int i=l;i<=r;i+=t)L[++cnt]=i,point[cnt]=i,R[cnt]=min(i+t-1,r);
    for(re int i=1;i<=cnt;++i)merge(L[i],R[i]);
    for(re int i=l;i<=r;++i){
        minn=2e9,mini=0;
        for(re int j=1;j<=cnt;++j){
            if(point[j]>R[j])continue;
            if(a[point[j]]<minn)minn=a[point[j]],mini=j;
        }
        tmp[i]=minn,point[mini]++;
    }
    for(re int i=l;i<=r;++i)a[i]=tmp[i];
}
il int read(){
    re int x=0,f=1,ch=getchar_unlocked();
    for(;!isdigit(ch);ch=getchar_unlocked())if(ch=='-')f=-1;
    for(;isdigit(ch);ch=getchar_unlocked())x=(x<<3)+(x<<1)+(ch^48);
    return x*f;
}
il void write(int x){
    x<0?x=-x,putchar_unlocked('-'):0;static short st[50],top(0);
    do st[++top]=x%10,x/=10;while(x);
    while(top)putchar_unlocked(st[top--]|48);
}
signed main(){
    n=read();
    for(re int i=1;i<=n;++i)a[i]=read();
    merge(1,n);
    for(re int i=1;i<=n;++i)write(a[i]),putchar_unlocked(' ');
    return 0;
}