1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C语言程序设计之标准库快速排序qsort函数用法示例

C语言程序设计之标准库快速排序qsort函数用法示例

时间:2022-01-09 09:16:23

相关推荐

C语言程序设计之标准库快速排序qsort函数用法示例

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,大功告成。。。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。