C语言中用qsort()快速排序

C语言中排序的算法有很多种,系统也提供了一个函数qsort()可以实现快速排序。原型如下: 
1 void qsort(void *base, size_t nmem, size_t size, int (*comp)(const void *, const void *));


它 根据comp所指向的函数所提供的顺序对base所指向的数组进行排序,nmem为参加排序的元素个数,size为每个元素所占的字节数。例如要对元素进 行升序排列,则定义comp所指向的函数为:如果其第一个参数比第二个参数小,则返回一个小于0的值,反之则返回一个大于0的值,如果相等,则返回0。
例:
01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int comp(const void *, const void *);
05  
06 int main(int argc, char *argv[])
07 {
08     int i;
09     int array[] = {6, 8, 2, 9, 1, 0};
10  
11     //此处有修改
12     //qsort(array, 6, sizeof(int), comp);
13     qsort(array, sizeof(array)/sizeof(*array), sizeof(int), comp);
14  
15     for (i = 0; i < 6; i ++) {
16         printf("%d\t", array[i]);
17     }
18     printf("\n");
19  
20     return 0;
21 }
22  
23 int comp(const void *p, const void *q)
24 {
25     return (*(int *)p - *(int *)q);
26 }

运行结果如下:
0 1 2 6 8 9 
原文地址:https://www.cnblogs.com/Mingxx/p/1968356.html