qsort()函数

作者:追风剑情 发布于:2020-3-23 9:35 分类:C

C中的快速排序函数原型:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
第1个参数是指针,指向待排序数组的首元素。ANSI C允许把指向任何数据类型的指针强制转换成指向void的指针,因此,qsort()的第1个实际参数可以引用任何类型的数组。
第2个参数是待排序项的数量。函数原型把该值转换为size_t类型。size_t定义在标准头文件中,是sizeof运算符返回的整数类型。
由于qsort()把第1个参数转换为void指针,所以qsort()不知道数组中每个元素的大小。为此,函数原型用第3个参数补偿这一信息,显式指明待排序数组中每个元素的大小。例如,如果排序double类型的数组,那么第3个参数应该是sizeof(double)。

注意 C和C++中的void*
C和C++对待指向void的指针有所不同。在这两种语言中,都可以把任何类型的指针赋给void类型的指针。但是,C++要求在把void*指针赋给任何类型的指针时必须进行强制类型转换。而C没有这样的要求。这种强制类型转换,在C中是可选的,但在C++中是必须的。因为两种语言都使用强制类型转换,所以遵循C++的要求也无不妥。将来如果要把该程序转成C++,就不必更改这部分代码。

示例

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. //#include <stdbool.h> //C99特性
  5. //#include <string.h>
  6. //#include <math.h>
  7. //#include <ctype.h>
  8. //#include <tgmath.h>
  9.  
  10. #define NUM 40
  11. void fillarray(double ar [], int n);
  12. void showarray(const double ar[], int n);
  13. int mycomp(const void* p1, const void* p2);
  14.  
  15. int main(int argc, char* argv[])
  16. {
  17. double vals[NUM];
  18. fillarray(vals, NUM);
  19. puts("Random list:");
  20. showarray(vals, NUM);
  21. qsort(vals, NUM, sizeof(double), mycomp);
  22. puts("\nSorted list:");
  23. showarray(vals, NUM);
  24.  
  25. system("pause");
  26. return 0; //main()函数退出时会隐式调用exit()
  27. }
  28.  
  29. void fillarray(double ar[], int n)
  30. {
  31. int index;
  32. for (index = 0; index < n; index++)
  33. ar[index] = (double)rand() / ((double)rand() + 0.01);
  34. }
  35.  
  36. void showarray(const double ar[], int n)
  37. {
  38. int index;
  39. for (index = 0; index < n; index++)
  40. {
  41. printf("%9.4f ", ar[index]);
  42. if (index % 6 == 5)
  43. putchar('\n');
  44. }
  45. if (index % 6 != 0)
  46. putchar('\n');
  47. }
  48.  
  49. /* 按从小到大的顺序排序 */
  50. int mycomp(const void* p1, const void* p2)
  51. {
  52. /* 要使用指向double的指针来访问这两个值 */
  53. const double* a1 = (const double*)p1;
  54. const double* a2 = (const double*)p2;
  55.  
  56. if (*a1 < *a2)
  57. return -1;
  58. else if (*a1 == *a2)
  59. return 0;
  60. else
  61. return 1;
  62.  
  63. //或者
  64. //return *(double*)p1 < *(double*)p2 ? -1 : 1;
  65.  
  66. //如果是比较字符串,可以使用strcmp()函数
  67. }

运行测试
1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号