qsort即快速怕排序函数,包含在头文件stdlib.h或search.h中,函数的声明如下所示:
void qsort( void *base, size_tnum, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
base: 数组其实地址 num:数组元素个数 width:每个元素占的字节数 compare:比较函数
elem1:Pointer to the key for the search elem2:Pointer to the array element to be compared with the key
qsort函数会在运行时调用compre函数进行数组间元素大小的比较。
compare函数的形式如下所示:
int (__cdecl *compare )(const void *elem1, const void *elem2 )
compare函数的返回值的正负与元素之间的大小关系如下所示:<0:elem1 less than elem2
=0:elem1 equivalent to elem2
>0:elem1 greater than elem2
下面几个例子是qsort函数的应用:
1.使用qsort对整数型数组排序
int isShort(const void *elem1, const void *elem2)
{
return *(int *)elem1 - *(int *)elem2;
}
int main()
{
int arr[] = {5, 3, 1, 8, 9, 4, 7, 10, 2, 6};
qsort(arr, 10, sizeof(int), isShort);
return 0;
}
2.使用qsort对字符型数组排序
int isShort(const void *elem1, const void *elem2)
{
return *(char *)elem1 - *(char *)elem2;
}
3.使用qsort对浮点型数组排序
int isShort(const void *elem1, const void *elem2)
{
return *(double *)elem1 < *(double *)elem2 ? -1 : 1;
}
3.使用qsort对结构体型数组排序
struct A {
int a;
int b;
};
若a相等,则按b进行排序,否则按a进行排序
int isShort(const void *elem1, const void *elem2)
{
struct A* obj1 = (struct A*)elem1;
struct A* obj2 = (struct A*)elem2;
if (obj1->a == obj2->a)
{
return obj1->b - obj2->b;
}
else
{
return obj1->a - obj2->a;
}
}
4.使用qsort对char*型数组排序
int isShort(const void *elem1, const void *elem2)
{
return strcmp(*(char **)elem1, *(char **)elem2);
}