分类: C/C++
2009-01-07 15:36:40
1,Syntax:
#include
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void*, const void *) );
2,qsort函数使用快速排序的方法,将buf中的数据按照compare定义的大小顺序进行排序。使用qsort前需要先定义compare函数。
3,例子:ACM, DNA Sorting
#include
typedef struct
{
char str[51];
int measure;
} STRMEAS;
STRMEAS g_seq[100];
int N, M;
//Pay attention to prototype of this function.
int fun_com(const void* a, const void* b)
{
STRMEAS *pa = (STRMEAS*) a;
STRMEAS *pb = (STRMEAS*) b;
return pa->measure - pb->measure;
}
fun_msr()
{
int i, j, k, m, msr;
char t;
for (k = 0; k < M; ++ k)
{
msr = 0;
STRMEAS sm;
//Compute measure for each string.
for (i = 0; i < N; ++ i)
{
sm = g_seq[k];
t = sm.str[i];
m = 0;
for (j = i + 1; j < N; ++ j)
{
if (t > sm.str[j])
++ m;
}
msr += m;
}
g_seq[k].measure = msr;
}
}
main()
{
int i;
scanf("%d%d", &N, &M);
for (i = 0; i < M; ++ i)
scanf("%s", g_seq[i].str);
fun_msr();
qsort(g_seq, M, sizeof(STRMEAS), fun_com);
for (i = 0; i < M; ++ i)
printf("%s\n", g_seq[i].str);
}