题目
给定N个(长整型范围内的)整数,要求输出从小到大排序后的结果。
本题旨在测试各种不同的排序算法在各种数据情况下的表现。各组测试数据特点如下:
数据1:只有1个元素;
数据2:11个不相同的整数,测试基本正确性;
数据3:103个随机整数;
数据4:104个随机整数;
数据5:105个随机整数;
数据6:105个顺序整数;
数据7:105个逆序整数;
数据8:105个基本有序的整数;
数据9:105个随机正整数,每个数字不超过1000。
输入格式:
输入第一行给出正整数N(≤10^5),随后一行给出N个(长整型范围内的)整数,其间以空格分隔。
输出格式:
在一行中输出从小到大排序后的结果,数字间以1个空格分隔,行末不得有多余空格。
输入样例:
11
4 981 10 -17 0 -20 29 50 8 43 -5
输出样例:
-20 -17 -5 0 4 8 10 29 43 50 981
各类排序算法
#include <stdio.h>
#define cutoff 100 //数值大小决定是否爆栈
void bubbleSort(int* a,int n);
void swap(int *a,int *b);
void outPut(int *a,int N);
void choseSort(int* a,int n);
void insertSort(int* a,int n);
void changeLenthInsertSort(int *a,int n,int d);
void shellSort(int *a,int n);
void SedgewickShellSort(int *a,int n);
int chosePivot(int *a,int l,int r);
void quickSort(int *a,int l,int r);
void quickSortStand(int* a,int n);
int main(){
//输入
int N;
scanf("%d",&N);
int *a=(int*)malloc(sizeof(int)*N);
for(int i=0;i<N;i++)
scanf("%d",&a[i]);
//排序方法
//bubbleSort(a,N);
//choseSort(a,N);
//insertSort(a,N);
//shellSort(a,N);
//SedgewickShellSort(a,N);
//quickSortStand(a,N);//会爆栈
//输出
outPut(a,N);
return 0;
}
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
void outPut(int *a,int N){
printf("%d",a[0]);
for(int i=1;i<N;i++)
printf(" %d",a[i]);
}
void bubbleSort(int* a,int n){
int f=1;
for(int i=1;i<n&&f;i++){
f=0;
for(int j=0;j<n-i;j++)
if(a[j]>a[j+1]){
swap(&a[j],&a[j+1]);
f=1;
}
}
}
void choseSort(int* a,int n){
int max;
int f=1;
for(int i=1;i<n&&f;i++){
max=0;
f=0;
for(int j=1;j<=n-i;j++){
if(a[j]>a[max])
max=j;
f=1;
}
if(f)
swap(&a[n-i],&a[max]);
}
}
void insertSort(int* a,int n){
int tmp,j;
for(int i=1;i<n;i++){
tmp=a[i];
for( j=i;j>0&&tmp<a[j-1];j--)
a[j]=a[j-1];
a[j]=tmp;
}
}
void changeLenthInsertSort(int *a,int n,int d){
int tmp,j;
for(int i=d;i<n;i++){
tmp=a[i];
for( j=i;j>=d&&tmp<a[j-d];j-=d)
a[j]=a[j-d];
a[j]=tmp;
}
}
void shellSort(int *a,int n){
for(int d=n/2;d>0;d/=2)
changeLenthInsertSort(a,n,d);
}
void SedgewickShellSort(int *a,int n){
int Sedgewick[]={146305 ,64769, 36289, 16001, 8929, 3905, 2161,929, 505, 209, 109, 41, 19, 5, 1, 0};
int i;
for ( i=0; Sedgewick[i]>=n; i++ );
for ( int D=Sedgewick[i]; D>0; D=Sedgewick[++i] )
changeLenthInsertSort(a,n,D);
}
int chosePivot(int *a,int l,int r){
int center=(r+l)/2;
if(a[l]>a[center])
swap(&a[l],&a[center]);
if(a[l]>a[r])
swap(&a[l],&a[r]);
if(a[center]>a[r]);
swap(&a[center],&a[r]);
swap(&a[r-1],&a[center]);
return a[r-1];
}
void quickSort(int* a,int l,int r){
if(cutoff<=r-l){
int pivot=chosePivot(a,l,r);
int i=l,j=r-1;
while(1){
while(a[++i]<pivot)
while(a[--j]>pivot)
if(i<j)
swap(&a[i],&a[j]);
else
break;
}
swap(&a[i],&a[r-1]);
quickSort(a,l,i-1);
quickSort(a,i+1,r);
}
else
insertSort(a+l,r-l+1);
}
void quickSortStand(int* a,int n){
quickSort(a,0,n-1);
}