跳到正文

算法·理论

O(n)排序

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

本排序由友链&巨佬一只爬行者提供。

pascal版(原版):

pascal
var n,i,t:longint;
    res,ord:array[0..1000000]of longword;
    a,b:array[0..1000000]of word;
    cnt:array[0..65535]of longint;
begin
  readln(n);
  for i:=1 to n do
  begin
    read(t);
    a[i]:=t>>16;            //就是t div 65536的卡常版
    b[i]:=t and (1<<16-1);  //就是t mod 65536的卡常版。
    inc(cnt[b[i]]);         //正式把读入的数拆成两个读进来
  end;
  for i:=0 to 65534 do
    inc(cnt[i+1],cnt[i]);   //我也不知道为啥CCF就是这样写的
  for i:=1 to n do
  begin
    ord[cnt[b[i]]]:=i;
    dec(cnt[b[i]]);
  end;
  fillchar(cnt,sizeof(cnt),0);
  for i:=1 to n do
    inc(cnt[a[i]]);
  for i:=0 to 65534 do
    inc(cnt[i+1],cnt[i]);
  for i:=n downto 1 do
  begin
    res[cnt[a[ord[i]]]]:=ord[i];
    dec(cnt[a[ord[i]]]);
  end;
  for i:=1 to n do
    write(a[res[i]]<<16+b[res[i]],' ');//输出的时候就把A乘上65536再加上B输出完事
end.

C++版(个人翻译):

C++
#include <iostream>
#include <cstring>
using namespace std;
int n, i, t;
int res[1000000], ord[1000000];
int a[1000000], b[1000000];
int cnt[65535];

int main( ){
	cin >> n;
	for(int i = 1; i <= n; i++){
		cin >> t;
		a[i] = t / 65536;
		b[i] = t % 65536;
		cnt[b[i]]++;
	}
	for(int i = 0; i < 65535; i++){
		cnt[i + 1] += cnt[i];
	}
	for(int i = 1; i <= n; i++){
		ord[cnt[b[i]]] = i;
		cnt[b[i]]--;
	}
	memset(cnt, 0, sizeof(cnt));
	for(int i = 1; i <= n; i++){
		cnt[a[i]]++;
	}
	for(int i = 0; i < 65535; i++){
		cnt[i + 1] += cnt[i];
	}
	for(int i = n; i >= 1; i--){
		res[cnt[a[ord[i]]]] = ord[i];
		cnt[a[ord[i]]]--;
	}
	for(int i = 1; i <= n; i++){
		cout << (a[res[i]] * 65536) + b[res[i]] << " ";
	}
	return 0;
}
原文