排序算法

//Twenty
#include<cstdio>
#include<iostream>
using namespace std;
int n,a[10000500],t[10000500],ans;

void ms(int a[],int t[],int l,int r) 
{
   if(l==r) return; 
   int m=(l+r)>>1; 
   ms(a,t,l,m);ms(a,t,m+1,r);
   int i=l,j=m+1,k=l;
   while(i<=m||j<=r){
     if(j>r||(i<=m&&a[i]<a[j])) t[k++]=a[i++];
     else {t[k++]=a[j++]; ans+=r-j+1;}
   }
   for(int i=l;i<=r;i++)
   a[i]=t[i];
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    cin>>a[i];
    ms(a,t,1,n);
    for(int i=1;i<=n;i++)
    cout<<a[i]<<" ";
    //cout<<ans<<endl;
    return 0;
}
归并排序
//Twenty
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<ctime>
#include<vector>
const int maxn=100000+50;
int a[maxn],n,k,kk,o[10]={1,1};
using namespace std;
inline int read(){
    int ret=0;char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    for(;ch>='0'&&ch<='9';ch=getchar()) ret=ret*10+ch-'0';
    return ret;
}
void qsort(int left,int right){
    int l=left,r=right;
    int m=a[l+rand()%((r-l+1)/2)];
    while(l<=r){
       while(a[l]<m) l++;
       while(a[r]>m) r--;
       if(l<=r) swap(a[l],a[r]),l++,r--;
    }
    if(l<right) qsort(l,right);
    if(r>left) qsort(left,r);
}
int main()
{
    srand(time(0));
   n=read();
   for(int i=1;i<=n;i++){
      a[i]=read();
   }
   qsort(1,n);
   for(int i=1;i<=n;i++)
    printf("%d ",a[i]);
   return 0;
}
快速排序
//Twenty
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<vector>
const int maxn=100000+50;
int a[maxn],n,k,kk,o[10]={1,1};
using namespace std;
inline int read(){
    int ret=0;char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    for(;ch>='0'&&ch<='9';ch=getchar()) ret=ret*10+ch-'0';
    return ret;
}
int get(int x,int y){
    return (x/o[y])%10;
}
void bucket_sort(){
    int tm,cout[10];
    int *bucket=(int*)malloc((n+1)*sizeof(int));
    for(kk=1;kk<=k;kk++){
        for(int i=0;i<=9;i++) cout[i]=0;
        for(int i=1;i<=n;i++){
          tm=get(a[i],kk);
          cout[tm]++;
        }
        for(int i=1;i<=9;i++) cout[i]+=cout[i-1];
        for(int i=n;i>=1;i--){
           tm=get(a[i],kk);
           bucket[cout[tm]]=a[i];
           cout[tm]--;
        }
        for(int i=1;i<=n;i++){
         a[i]=bucket[i];
        }
    }
    free(bucket);
}
int main()
{
   n=read();
   for(int i=1;i<=n;i++){
      a[i]=read();
      if(a[i]>kk) kk=a[i];
   }
   while(kk)
    kk/=10,k++; 
   for(int i=2;i<=k;i++)
     o[i]=o[i-1]*10;
   bucket_sort();
   for(int i=1;i<=n;i++)
    printf("%d ",a[i]);
   return 0;
}
/*
10
5 43 78 324 12 64 98 72 54 31
*/
桶排序

 

posted @ 2017-09-04 17:23  啊宸  阅读(135)  评论(0编辑  收藏  举报