C语言程序设计之标准库快速排序qsort函数用法示例
生活随笔
收集整理的這篇文章主要介紹了
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,大功告成。。。
總結
以上是生活随笔為你收集整理的C语言程序设计之标准库快速排序qsort函数用法示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pthread多线程编程之查看Pthre
- 下一篇: 多线程编程之死锁已经死锁产生的原因