快速排序和堆排序模板
不得不承认在初赛来临前复习这些很丢人……
好吧,其实我觉得可以手推,不过放个板子保险一点。
因为我怂
Quick_Sort
using namespace std;
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <algorithm>
int n;
int a[200001];
void qsort(int l,int r){
int i=l,j=r,mid=a[l+rand()%(r-l+1)];
do{
while (a[j]>mid) j--;
while (a[i]<mid) i++;
if (i<=j){
swap(a[i],a[j]);
i++,j--;
}
}
while (i<=j);
if (i<r)
qsort(i,r);
if (l<j)
qsort(l,j);
}
int main(){
scanf("%d",&n);
for (int i=1;i<=n;++i)
scanf("%d",&a[i]);
srand(time(0));
qsort(1,n);
for (int i=1;i<=n;++i)
printf("%d\n",a[i]);
return 0;
}
Heap_Sort
//heap(The largest value is on the top.)
using namespace std;
#include <cstdio>
#include <cstring>
#include <algorithm>
int n,m;
int h[200001];
void up(int x){
while (x!=1 && h[x]>h[x>>1]){
swap(h[x],h[x>>1]);
x>>=1;
}
}
void down(int x){
int k;
while ((k=x<<1)<=n){
if ((k|1)<=n && h[k|1]>h[k])
k|=1;
if (h[x]>h[k])
return;
swap(h[x],h[k]);
x=k;
}
}
void pop(){
swap(h[1],h[n]);
n--;
down(1);
}
int main(){
scanf("%d",&n);
m=n;
for (int i=1;i<=m;++i)
scanf("%d",&h[i]);
for (int i=m>>1;i>=1;--i)
down(i);
for (int i=m;i>=1;--i)
pop();
for (int i=1;i<=m;++i)
printf("%d\n",h[i]);
return 0;
}