Chinaunix首页 | 论坛 | 博客
  • 博客访问: 185210
  • 博文数量: 49
  • 博客积分: 635
  • 博客等级: 中士
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-25 12:58
文章分类

全部博文(49)

文章存档

2012年(9)

2011年(40)

分类: C/C++

2011-08-31 15:41:54

qsort()是标准C自带的快排函数,函数原型及相关参数说明如下:
  1. SYNOPSIS
  2. #include <stdlib.h>
  3. void qsort(void *base, size_t nmemb, size_t size,int(*compar)(const void *, const void *));
  4. DESCRIPTION
  5.        The qsort() function sorts an array with nmemb elements of size size. The base argument points to array.
  6.     The contents of the array are sorted in ascending order according to a comparison functionto by compar, which is called with two arguments that point to the objects being compared.
  7.        The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than,equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
注意:qsort比较函数的参数是被比较对象的指针。
结构体定义如下:

  1. struct mystruct{
  2.    int no;
  3.    char ***;
  4. };
定义一个结构体数组:
  1. 13 int i;
  2.  14 struct mystruct m1 = {1, 'm'};
  3.  15 struct mystruct m2 = {2, 'w'};
  4.  16 struct mystruct m3 = {0, 'm'};
  5.  21 struct mystruct arr[] = {m1, m2, m3};
比较函数定义:
  1. 29 int compare(const void *p1, const void *p2)
  2.  30 {
  3.  31 return ( *(const struct mystruct *)p1).no - (*(const struct mystruct *)p2).no;
  4.  32 }
注意:比较函数必须定义为接受一般指针类型,所以,对指针的转换就放在函数体内。p1 , p2为指向比较对象,结构体的指针,转换时要注意。


如果定义一个结构体指针数组,则比较函数更改如下:

  1. 35 int compare(const void *p1, const void *p2)
  2.  36 {
  3.  37 struct mystruct *sp1 = *(struct mystruct * const *)p1;
  4.  38 struct mystruct *sp2 = *(struct mystruct * const *)p2;
  5.  39 //return ((*(struct mystruct * const *)p1)->no) - ((*(struct mystruct * const *))->no);
  6.  40 return sp1->no - sp2->no;
  7.  41 }
总结:
1.qsort函数不返回
2.比较函数的返回值为int
3.比较函数的参数是指针,指向被比较对象
4.比较函数的参数是void 指针
5.用结构体数组时, size为sizeof(struct mystruct),使用结构体指针数组时,为sizeof(struct mystruct *)


阅读(6974) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~