qsort的用法

来源:互联网 发布:知乎删除回答 编辑:程序博客网 时间:2024/04/28 05:22

<本文中排序都是采用的从小到大排序> 

qsort  包含在头文件 #include<stdlib.h>

qsort ( 哪个 , 长度 , 大小, cmp)



一、对int类型数组排序 


[cpp] view plain copy
 print?
  1. int num[100];   
  2.   
  3. int cmp ( const void *a , const void *b )   
  4. {   
  5.     return *(int *)a - *(int *)b;   
  6. }   
  7.   
  8. qsort(num,100,sizeof(num[0]),cmp);   




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


[cpp] view plain copy
 print?
  1. char word[100];   
  2.   
  3. int cmp( const void *a , const void *b )   
  4. {   
  5.     return *(char *)a - *(char *)b;   
  6. }   
  7.   
  8. qsort(word,100,sizeof(word[0]),cmp);   




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


[cpp] view plain copy
 print?
  1. double in[100];   
  2.   
  3. int cmp( const void *a , const void *b )   
  4. {   
  5.     return *(double *)a > *(double *)b ? 1 : -1;   
  6. }   
  7.   
  8. qsort(in,100,sizeof(in[0]),cmp);   




四、对结构体一级排序 


[cpp] view plain copy
 print?
  1. struct In   
  2. {   
  3.     double data;   
  4.     int other;   
  5. }s[100]   
  6.   
  7. //按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写   
  8.   
  9. int cmp( const void *a ,const void *b)   
  10. {   
  11.     return (*(In *)a).data > (*(In *)b).data ? 1 : -1;   
  12. }   
  13.   
  14. qsort(s,100,sizeof(s[0]),cmp);   




五、对结构体二级排序 


[cpp] view plain copy
 print?
  1. struct In   
  2. {   
  3.     int x;   
  4.     int y;   
  5. }s[100];   
  6.   
  7. //按照x从小到大排序,当x相等时按照y从大到小排序   
  8.   
  9. int cmp( const void *a , const void *b )   
  10. {   
  11.     struct In *c = (In *)a;   
  12.     struct In *d = (In *)b;   
  13.     if(c->x != d->x) return c->x - d->x;   
  14.     else return d->y - c->y;   
  15. }   
  16.   
  17. qsort(s,100,sizeof(s[0]),cmp);   




六、对字符串进行排序 



[cpp] view plain copy
 print?
  1. struct In   
  2. {   
  3.     int data;   
  4.     char str[100];   
  5. }s[100];   
  6.   
  7. //按照结构体中字符串str的字典顺序排序   
  8.   
  9. int cmp ( const void *a , const void *b )   
  10. {   
  11.     return strcmp( (*(In *)a)->str , (*(In *)b)->str );   
  12. }   
  13.   
  14. qsort(s,100,sizeof(s[0]),cmp);   




七、计算几何中求凸包的cmp 

 

[cpp] view plain copy
 print?
  1. int cmp(const void *a,const void *b) //重点cmp函数,把除了1点外的所有点,旋转角度排序   
  2. {   
  3.     struct point *c=(point *)a;   
  4.     struct point *d=(point *)b;   
  5.     if( calc(*c,*d,p[1]) < 0)  
  6.          return 1;   
  7.     else  //如果在一条直线上,则把远的放在前面   
  8.         if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y))  
  9.             return 1;   
  10.             else return -1;   
  11. }   

0 0
原创粉丝点击