qsort函数各种排序的模拟实现

这篇博客介绍了如何使用C语言实现快速排序算法,并展示了针对不同数据类型(整数、结构体)的排序比较函数。内容包括:1.基本的整数数组排序;2.按结构体名字首字母排序;3.按结构体中成绩排序;4.按结构体中年龄排序。通过my_qsort函数,实现了通用的快速排序逻辑。
//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当成个万能接收的指针
			}
		}
	}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值