七種qsort排序方法<本文中排序都是採用的從小到大排序>一、對int類型數組排序C++代碼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類型)C++代碼char word[100]; Sample:int cmp( const void *a , const void *b ) { return *(char *)a – *(char*)b; } qsort(word,100,sizeof(word[0]),cmp) 三、對double類型數組排序(特別要注意)C++代碼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); 四、對結構體一級排序C++代碼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); 五、對結構體二級排序C++代碼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); 六、對字串進行排序C++代碼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); 七、計算幾何中求凸包的cmpC++代碼int cmp(const void *a,const void *b) //重點cmp函數,把除了1點外的所有點,旋轉角度排序 { struct point *c=(point *)a; struct point *d=(point *)b; if( calc(*c,*d,p[1]) < 0) return 1; else 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)) //如果在一條直線上,則把遠的放在前面 return 1; else return -1; } PS: 其中的qsort函數包含在的標頭檔裡,strcmp包含在的標頭檔裡