在常用算法總排序是最常用的算法之一!而快排在c 的 stdlib庫中是有現成的封裝對于我們寫算法是提供了友善之處的!
一 、對int類型數組排序
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
qsort(arry, n, sizeof(arry[0]), cmp);
qsort(指向一個要排序數組的首位址
, 指要排序數組的元素個數
, 指每個元素的大小
, cmp);
這個是一個從大到小的排序如果要從小到大排序可以講cmp函數改為如下:
int cmp(constvoid *a,constvoid *b)
{
return*(int *)a - *(int *)b;
}
二、對char類型數組排序(同int類型)
char word[100];
int cmp( const void *a , const void *b )
{
return *(char *)a - *(int *)b;
}
qsort(word,100,sizeof(word[0]),cmp);
三、對double類型數組排序
double in[100];
return *(double *)a > *(double *)b ? 1 : -1;
qsort(in,100,sizeof(in[0]),cmp);
四、對結構體一級排序
struct sample
double data;
int other;
}s[100]
//按照data的值從小到大将結構體排序
int cmp( const void *a ,const void *b)
return (*(sample *)a).data > (*(sample *)b).data ? 1 : -1;
qsort(s,100,sizeof(s[0]),cmp);
五、對結構體二級排序
int x;
int y;
}s[100];
//按照x從小到大排序,當x相等時按照y從大到小排序
struct sample *c = (sample *)a;
struct sample *d = (sample *)b;
if(c->x != d->x) return c->x - d->x;
else return d->y - c->y;
六、對字元串進行排序
int data;
char str[100];
//按照結構體中字元串str的字典順序排序
int cmp ( const void *a , const void *b )
return strcmp( (*(sample *)a)->str , (*(sample *)b)->str );