快速排序函数函数原型:

void qsort(void *base, size_t num, size_t width, int(*compare)(const void *num1, const void *num2));

参数:1、待排序的数组的首地址

      2、数组中待排序元素的个数

      3、各元素占用空间的大小

      4、指向比较函数的指针,用于确定排序的顺序

compare函数的原型:int compare(const void *elem1,const void *elem2)

compare函数的返回值描述
小于0elem1将排在elem2的前面
等于0elem1等于elem2
大于0elem1将排在elem2的后面

1、×××数组的比较函数:

/*×××数组比较函数*/
int IntCmp(const void *a, const void *b)
{
	return (*(int *)a > *(int *)b) ? 1 : -1;
}

2、浮点型数组比较函数

/*浮点型数组比较函数*/
int DoubleCmp(const void *a, const void *b)
{
	return ((*(double *)a - *(double *)b)>0) ? 1 : -1;
}

3、字符型数组比较函数

/*字符型数组比较函数*/
int CharCmp(const void *a, const void *b)
{
	return (*(char *)a > *(char *)b) ? 1 : -1;
}

4、字符串数组比较函数

/*字符串数组比较函数*/
int StrCmp(const void *str1, const void *str2)
{
	return (strcmp((char *)(*(int *)str1), (char *)(*(int *)str2)) > 0) ? 1 : -1;
}

5、结构体类型比较函数,假设有以下结构体,并以学生成绩为依据对学生姓名按照成绩的一定顺续输出

#include <stdio.h>
#include <stdlib.h>

/*学生类型的结构体*/
typedef struct Stu
{
	char name[20];//学生姓名
	int sorce;  //学生成绩
}Stu;

/*结构体类型比较函数*/
int StcCmp(const void *stc1, const void *stc2)
{
	return ((*(Stu *)stc1).sorce > (*(Stu *)stc2).sorce) ? 1 : -1;
}

int main()
{
	Stu stu[] = { { "lisi", 70 }, { "zhangsan", 35 }, { "wangwu", 50 } };
	qsort(stu, sizeof(stu) / sizeof(stu[0]), sizeof(stu[0]), StcCmp);
	for (int i = 0; i < sizeof(stu) / sizeof(stu[0]); i++)
	{
		printf("%s\n", stu[i].name);
	}
	system("pause");
	return 0;
}

结构体类型排序运行结果:

wKiom1ZYWHTAcjvLAAB6lYWpA2g989.png