我們查MSDN可以看到裡面對qsort有如下描述:http://hi.csdn.net/tsyj810883979
void qsort(void *base, size_t num,size_t width,int (__cdecl *compare )(const void *, const void *));
base Start of target array.
-
num Array size in elements.
-
width Element size in bytes.
-
compare Comparison function. The first parameter is a pointer to the key for the search and the second parameter is a pointer to the array element to be compared with the key.
本文內容來自:濤濤的部落格http://hi.csdn.net/tsyj810883979
看了以上描述應該對此函數有所瞭解了,但是compare似乎還是有點困難,現總結如下:
<本文中排序都是採用的從小到大排序>
一、對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);
六、對字串進行排序
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
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函數包含在<stdlib.h>的標頭檔裡,strcmp包含在<string.h>的標頭檔裡