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。
例:
04 |
int comp( const void *, const void *); |
06 |
int main( int argc, char *argv[]) |
09 |
int array[] = {6, 8, 2, 9, 1, 0}; |
13 |
qsort (array, sizeof (array)/ sizeof (*array), sizeof ( int ), comp); |
15 |
for (i = 0; i < 6; i ++) { |
16 |
printf ( "%d\t" , array[i]); |
23 |
int comp( const void *p, const void *q) |
25 |
return (*( int *)p - *( int *)q); |
运行结果如下:
0 1 2 6 8 9