//qsort函数的模拟和使用
#include <stdio.h>
#include <string.h>
//qsort的各种排序取决于cmp函数的内容
//1.数组元素的大小排序
int cmp(void const* e1, void const* e2)
{
return *(int*)e1 - *(int*)e2;
}
//2.结构体名字首字母的排序
int cmp(void const* e1, void const* e2)
{
return strcmp((*(struct stu*)e1).name , (* (struct stu*)e2).name);
}
//3.结构体中成绩的大小排序
int cmp(void const* e1, void const* e2)
{
return (*(struct stu*)e2).score- (*(struct stu*)e1).score;
}
//4.结构体中年龄的大小比较
int cmp(void const* e1, void const* e2)
{
return (*(struct stu*)e2).age- (*(struct stu*)e1).age;
}
//公共部分
struct stu
{
char name[100];
int age;
float score;
};
void swap(char *buf1, char* buf2,int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;//一点点一点点的交换
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void my_qsort(void* base, int nums, int width, int(*cmp)(void const* e1, void const* e2))
{
int i = 0;
for (i = 0; i < nums - 1; i++)
{
int j = 0;
for (j = 0; j < nums - 1 - i; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)//char*强转是因为传过来的base是void*不确定是类型
{
swap((char*)base + j * width, (char*)base + (j + 1) * width,width);//,为了后续计算,才强转成一个char*类型
//用void*类型的base接收是为了把base当成个万能接收的指针
}
}
}
}
qsort函数各种排序的模拟实现
最新推荐文章于 2025-12-12 16:37:00 发布
这篇博客介绍了如何使用C语言实现快速排序算法,并展示了针对不同数据类型(整数、结构体)的排序比较函数。内容包括:1.基本的整数数组排序;2.按结构体名字首字母排序;3.按结构体中成绩排序;4.按结构体中年龄排序。通过my_qsort函数,实现了通用的快速排序逻辑。
7298

被折叠的 条评论
为什么被折叠?



