现在的位置: 首页 > 综合 > 正文

qsort()例子

2013年07月06日 ⁄ 综合 ⁄ 共 965字 ⁄ 字号 评论关闭

man-page

http://www.kernel.org/doc/man-pages/online/pages/man3/qsort.3.html

void qsort(void *base, size_t nmemb, size_t size,int(*compar)(const void *p1, const void *p2));

The contents of the array are sorted in ascending order(升序) according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared

即:如果compar返回值大于0,则将p1和p2交换;否则,p1和p2顺序不变

//整形数组:(升序)
int arr[9999];
qsort(arr, n, sizeof(int), compare);
int compare(const void *a, const void *b)
{
	return ( *((int *)a) - *((int *)b) );
}


//结构体数组:(升序)
typedef struct
{
	char str[51];
	int unsortedness;
}DNA;
DNA dna[100];
qsort(dna, m, sizeof(DNA),compare);
int compare(const void *a, const void *b)
{
	return ( ((DNA *)a)->unsortedness - ((DNA *)b)->unsortedness );
	/*	or return ( (*(DNA *)a).unsortedness - (*(DNA *)b).unsortedness ); */
}


//结构体数组:(降序)
typedef struct
{
    int value;
    int weight;
    double per;//value / weignt
    int num;
}Coin;
Coin co[501];
qsort(co, n, sizeof(Coin), compare);
int compare(const void *p1, const void *p2)
{
    return ((Coin *)p1)->per < ((Coin *)p2)->per ? 1 : -1;//前 < 后,则交换
}

抱歉!评论已关闭.