C语言程序设计之标准库快速排序qsort函数,排序效率高,使用方便,太棒了。
qsort函数定义如下:
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
qsort函数示例,排序点,按距离排序。直接上代码:
#include <stdio.h>
#include <stdlib.h>
struct point { int x; int y; };
int my_dist_cmp(const void* i, const void* j)
{
struct point* a = (struct point*)i;
struct point* b = (struct point*)j;
return ((a->x) * (a->x) + (a->y) * (a->y)) - ((b->x) * (b->x) + (b->y) * (b->y));
}
int main(void)
{
struct point points[4] = { {10,5},{0,0},{-4,-5},{5,10} };
printf("排序前的点:\n");
for (int i = 0; i < 4; i++) {
printf("(%d, %d) ", points[i].x, points[i].y);
}
printf("\n");
qsort(points, 4, sizeof(struct point), my_dist_cmp);
printf("排序后的点:\n");
for (int i = 0; i < 4; i++) {
printf("(%d, %d) ", points[i].x, points[i].y);
}
printf("\n");
return(0);
}
运行结果:
E:\Workspace>tcc -run hello.c
排序前的点:
(10, 5) (0, 0) (-4, -5) (5, 10)
排序后的点:
(0, 0) (-4, -5) (5, 10) (10, 5)
至此,OK,大功告成。。。
本文介绍C语言标准库中的qsort函数,并通过一个实际案例展示如何使用该函数对结构体数组进行排序。示例中按照点到原点的距离对点进行排序。
4278





