void qsort(void *base,int nelem,unsigned int width,
int (*mycompare)(const void *,const void *));
base:待排序数组的起始地址;
nelem:待排序数组的元素个数;
width:待排序数组的每个元素的大小(sizeof(T) (T代表变量名,如int,double,等))
最后就是自定义的比较函数了。
排序就是一个不断比较并交换位置的过程。qsort函数在执行期间通过*mycompare指针调用比较函数,调用时将要比较的两个元素的地址传给比较函数,然后根据比较函数的返回值判断这两个元素哪个更应该排在前面。
int 比较函数名(const void e1,const void e2);
比较函数的编写规则:
1.如果 e1应该在e2前面,返回值应该为负整数;
2.如果 e1应该在e2后面,返回值应该为正整数;
3.如果e1与e2谁在前谁在后都可,那么函数返回值应该为0。
举个例子:将23,47,134,9,435这几个数,按个位数从小到大排序。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <ctype.h>
#include <cstdlib>
using namespace std;
int mycompare(const void *e1,const void *e2)
{
unsigned int *p1,*p2;
p1=(unsigned int *)e1;//e1是void*类型,*e1无定义,这里是一个强制转换
p2=(unsigned int *)e2;
return (*p1)%10-(*p2)%10;//按个位从小到大的话模10就行了,返回值正负参照compare函数的编写规则
}
int main()
{
unsigned int s[5]={9,23,134,435,47};
qsort(s,5,sizeof(unsigned int),mycompare);
for(int i=0;i<5;i++)printf("%d\n",s[i]);
return 0;
}
输出结果:
23
134
435
47
9