稳定版快排
pascal吧
全部回复
仅看楼主
level 4
qxl200155 楼主
program xxx;
var
//注:快排是不稳定的,最坏情况下运行效率为O(n²),和冒泡排序,选择排序等一样快。
//NOIP中一般可以忽略这个问题,但是就怕老师故意出个最坏情况的数据。。。
//解决这个问题一般用随机化处理,请自行百度随机化快排
//还有一种方法就是下面的稳定快排,但是要牺牲一些空间
//稳定版快排多了一个数组来存储标号。
a,num:array[1..1000000]of longint;
i,j,k,kk,h:longint;
n:longint;
procedure qsort(head,leg:integer);
{var
i,j,k,kk,h:integer;} //设为了全局变量,节省栈空间
begin
i:=head;
j:=leg;
k:=a[(i+j)div 2];
kk:=num[(i+j)div 2];
repeat
while ((a[i]=k) and (num[i]<kk)) or (a[i]<k) do inc(i);
while ((a[j]=k) and (num[j]>kk)) or (a[j]>k) do dec(j);
if i<=j then
begin
h:=a[i];
a[i]:=a[j];
a[j]:=h;
h:=num[i];
num[i]:=num[j];
num[j]:=h;
inc(i);
dec(j);
end;
until i>j;
if head<j then qsort(head,j);
if i<leg then qsort(i,leg);
end;
begin
readln (n);
for i:=1 to n do
begin
read (a[i]);
num[i]:=i;
end;
qsort (1,n);
for i:=1 to n do write (a[i]);
readln;
end.
2014年10月20日 11点10分 1
level 5
敢问试验过没有[疑问] 求运行时间和内存占用
2014年10月20日 13点10分 2
level 12
“稳定”(stable)这个词似乎不是这个意思……
2014年10月21日 13点10分 3
+1
2014年10月21日 13点10分
+1
2017年08月18日 05点08分
level 1
弱弱地问一句:为什么不打堆排?毕竟都已经打了这么长的代码了……
2014年10月24日 02点10分 4
level 7
[开心]稳定的意思 似乎是?
坐等楼下大婶们来解释

1.直接random不好么,
2.常数优化 div 2 换成 shr 1吧。。
2014年10月24日 05点10分 5
level 9
orz!
2014年10月26日 04点10分 6
level 7
稳定快排,在O(N2)
2017年05月21日 02点05分 8
1