跳到正文

算法·理论

一个排序

zzzMVP约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月1日
更新
2026年4月1日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

本篇文章介绍一个自己研究的新的排序方法,包括他的普通版本,优化版本。

背景

当时正在写数学作业,主题是中位数。因为这个主题有大量的排序,所以我急需一个空间又小速度又快的排序方法。 在多次尝试后,找到了这个排序方法。

细节

这是利用一个双端队列进行的排序,最快能到 O(n)O(n),最慢会到 O(n2)O(n^2),但平均是 O(nn)O(n \sqrt{\sqrt n})。

维护一个双端队列,并遍历需要排序的数组。当当前这个数如果小于等于这个双端队列的头,就放入双端队列的头部。否则判断当前这个数是否大于等于这个双端队列的尾部,如果大于就放入队尾。(代码17至26行)

遍历完后,要将队列里的数返回原数组。因为队头永远是此次s

标亮部分为排序

C++
#include<iostream>
#include<vector>
#include<deque>
using namespace std;

void sort(vector<int> &np ,int s, int e){
	deque<int> q;
	vector<int> next(e - s + 2), a(e - s + 2);
	next[0] = 1;
	for(int i = s; i <= e; i ++){
		next[i - s + 1] = i - s + 2;
		a[i - s + 1] = np[i];
	}
	int l = s, r = e;
	while(next[0] <= e - s){
		for(int i = next[0], last = 0; i <= e - s; i = next[i]){
			if(q.empty() || a[i] <= q.front()){
				q.push_front(a[i]);
				next[last] = next[i];
			}
			else if(a[i] >= q.back()){
				q.push_back(a[i]);
				next[last] = next[i];
			}
			else last = i;
		}

		int minn = q.front(), maxn = q.back();
		while(!q.empty() && q.front() == minn){
			np[l ++] = q.front();
			q.pop_front();
		}
		while(!q.empty() && q.back() == maxn){
			np[-- r] = q.back();
			q.pop_back();
		}
	}
	while(!q.empty()){
		np[l ++] = q.front();
		q.pop_front();
	}
}

int main(){
	cin.tie(nullptr) -> sync_with_stdio(0);
	int n;
	cin >> n;
	vector<int> a(n);
	for(auto &x : a) cin >> x;
	sort(a, 0, n);
	for(auto &x : a) cout << x << ' ';
}
原文