C语言中排序的算法有很多种,系统也提供了一个函数qsort()可以实现快速排序。原型如下:
void qsort(void *base, size_t nmem, size_t size, int (*comp)(const void *, const void *));
它 根据comp所指向的函数所提供的顺序对base所指向的数组进行排序,nmem为参加排序的元素个数,size为每个元素所占的字节数。例 如要 对元素进行升序排列,则定义comp所指向的函数为:如果其第一个参数比第二个参数小,则返回一个小于0的值,反之则返回一个大于0的值,如果相等,则返 回0。
例:
#include <stdio.h>
#include <stdlib.h>
int comp(const void *, const void *);
int main(int argc, char *argv[])
{
int i;
int array[] = {6, 8, 2, 9, 1, 0};
qsort(array, 6, sizeof(int), comp);
for (i = 0; i < 6; i ++) {
printf("%d/t", array[i]);
}
printf("/n");
return 0;
}
int comp(const void *p, const void *q)
{
return (*(int *)p - *(int *)q);
}
运行结果如下:
0 1 2 6 8 9
C语言qsort函数详解
本文详细介绍了C语言中qsort函数的使用方法,包括其原型、参数解释及如何通过自定义比较函数实现数组排序。并通过一个具体示例展示了如何使用qsort函数对整型数组进行升序排列。
1385

被折叠的 条评论
为什么被折叠?



