实例介绍C/C++qsort()快速排序的用法
来源:优易学  2011-11-9 14:35:46   【优易学:中国教育考试门户网】   资料下载   IT书店

  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

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训