一:描述
qsort函數包含在<stdlib.h>的頭文件,能夠對數組實現快排
二:函數聲明與參數解釋
void qsort( void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *) );
數組名是 base
數組的個數是 nmemb
每個數組元素的大小是 size
函數指針爲 compare,決定了排序的順序
返回值:無
三:compare的實現規則
compar參數指向一個比較兩個元素的函數。比較函數的原型應該像下面這樣。注意兩個形參必須是const void *型,同時在調用compar 函數(compar實質爲函數指針,這裏稱它所指向的函數也爲compar)時,傳入的實參也必須轉換成const void *型。在compar函數內部會將const void *型轉換成實際類型
int compar(const void *p1, const void *p2);
如果compar返回值小於0(< 0),那麼p1所指向元素會被排在p2所指向元素的前面
如果compar返回值等於0(= 0),那麼p1所指向元素與p2所指向元素的順序不確定
如果compar返回值大於0(> 0),那麼p1所指向元素會被排在p2所指向元素的後面
因此,如果想讓qsort()進行從小到大(升序)排序,那麼一個通用的compar函數可以寫成這樣:
int compareMyType (const void * a, const void * b)
{
if ( *(MyType*)a < *(MyType*)b ) return -1;
if ( *(MyType*)a == *(MyType*)b ) return 0;
if ( *(MyType*)a > *(MyType*)b ) return 1;
}
四:實例
4.1 對int char l類型進行排序
int num[100];
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
qsort(num,100,sizeof(num[0]),cmp);
4.2 對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);
4.3 對結構體一級排序
struct In
{
double data;
int other;
}s[100];
int cmp( const void *a ,const void *b)
{
return (*(struct In *)a)->data > (*(struct In *)b)->data ? 1 : -1;
}
qsort(s,100,sizeof(s[0]),cmp);
4.4 對結構體二級排序
struct In
{
int x;
int y;
}s[100];
//按照x從小到大排序,當x相等時按照y從大到小排序
int cmp( const void *a , const void *b )
{
struct In *c = (struct In *)a;
struct In *d = (struct 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);
4.5 對字符串排序
struct In
{
int data;
char str[100];
}s[100];
//按照結構體中字符串str的字典順序排序
int cmp ( const void *a , const void *b )
{
return strcmp( (*(struct In *)a)->str , (*(struct In *)b)->str );
}
qsort(s,100,sizeof(s[0]),cmp);