qsort排序

来源:互联网 发布:sas数据分析 编辑:程序博客网 时间:2024/04/30 13:59

 功 能: 使用快速排序例程进行排序   

用 法:   void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));   

参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针,用于确定排序的顺序

一、对int类型数组排序

int num[100]; Sample: int cmp ( const void *a , const void *b ) {  return *(int *)a - *(int *)b; } qsort(num,100,sizeof(num[0]),cmp); 

二、对char类型数组排序(同int类型)

char word[100]; Sample: int cmp( const void *a , const void *b ) {  return *(char *)a - *(int *)b; } qsort(word,100,sizeof(word[0]),cmp);  

三、对double类型数组排序(特别要注意) 

double in[100]; int cmp( const void *a , const void *b ) {  return *(double *)a > *(double *)b ? 1 : -1; } qsort(in,100,sizeof(in[0]),cmp); 

四、对结构体一级排序 

struct In {  double data;    int other; }s[100]; //按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写 int cmp( const void *a ,const void *B) {  return (*(In *)a)->data > (*(In *)B)->data ? 1 : -1; } qsort(s,100,sizeof(s[0]),cmp); 

五、对结构体二级排序 

struct In {  int x;   int y; }s[100]; //按照x从小到大排序,当x相等时按照y从大到小排序 int cmp( const void *a , const void *b ) {  struct In *c = (In *)a;    struct In *d = (In *)b;    if(c->x != d->x) return c->x - d->x;    else return d->y - c->y; } qsort(s,100,sizeof(s[0]),cmp); 

例题1:nyist 240(小明的调查统计)题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=240

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;#define max 100005struct paim{   int gd;    int xh;    int cs;    int pm;};/*bool comp(paim x,paim y)  //sort排序{   if(x.gd!=y.gd) return x.gd>y.gd;     if(x.gd==y.gd&&x.cs!=y.cs) return x.cs<y.cs;    if(x.gd==y.gd&&x.cs==y.cs&&x.xh!=y.xh) return x.xh<y.xh;} */ int comp( const void *a , const void *b ) {  struct paim *c=(paim *)a;    struct paim *d=(paim *)b;    if(c->gd!=d->gd) return d->gd-c->gd;    if(c->gd==d->gd&&c->cs!=d->cs) return c->cs-d->cs;   if(c->gd==d->gd&&c->cs==d->cs&&c->xh!=d->xh) return c->xh-d->xh; } int main(){   int n,m,y,t,num=0,i,j,k;    cin>>n>>m;    paim a[max];    for(i=1;i<=n;i++)    {  scanf("%d",&y);       for(j=1;j<=y;j++)       { scanf("%d",&t);         a[num].gd=t;         a[num].xh=j;         a[num].cs=i;         num++;       }    }    //sort(a,a+num,comp);     qsort(a,num,sizeof(a[0]),comp);     a[0].pm=1;     for(i=1;i<num;i++)    { if(a[i].gd!=a[i-1].gd)  a[i].pm=a[i-1].pm+1;      else  a[i].pm=a[i-1].pm;    }    for(i=0;i<m;i++)    { scanf("%d",&k);      for(j=0;j<num;j++)      { if(a[j].pm==k) cout<<a[j].cs<<" "<<a[j].xh<<endl;        else if(a[j].pm>k) break;      }    }    return 0;}

六、对字符串进行排序

struct In{   int data;     char str[100]; }s[100]; //按照结构体中字符串str的字典顺序排序 int cmp ( const void *a , const void *b ) {   return strcmp( (*(In *)a)->str , (*(In *)B)->str ); } qsort(s,100,sizeof(s[0]),cmp); 

七、计算几何中求凸包的cmp (略,前面的博文中有凸包模板)

 

 


 

 

 

 

 

原创粉丝点击