close

說明:陣列基礎的快速排序法函數,陣列是參數 base,n 是陣列大小,size 是每個
元素的大小,最後的參數是指向函數的指標,這是比較元素大小的函數( 即上面
compare() 函數)。

舉例:

六種qsort排序方法

<本文中排序都是採用的從小到大排序>

一、對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);



七、對字符串進行排序

呼叫
qsort( (void*) array , Num , sizeof( char* ) , compareString );
定義
int compareString(const void *a, const void *b)
{
return strcmp(*(char **)a, *(char **)b);
}

//char**)表示後面是一個指向char*資料形態的指標, 而char*在C裡多半當做字串使用, 因此你可以想成是String*, 也就是:

*((String*)p1)

從一個指向字串的指標裡, 取出它所指向的字串. 最後不就是用strcmp比對兩個字串

arrow
arrow
    文章標籤
    排序 QSORT
    全站熱搜

    winage 發表在 痞客邦 留言(0) 人氣()