模拟qsort(快排实现)写的bubble_qsort(冒泡实现)

分析:最近学习到了qsort函数,真是太方便了,据说是用快排实现的,可以对很多类型的数组进行排序,我就想自己模拟实现一个(快排还没学,而且快排实现起来比冒泡可能要麻烦一点,重要的是整理思路,就用冒泡排序模拟了一个)。

思路都在代码里面了,需要注意的点就是写swap函数的时候交换的是每个地址里面的内容而不是交换地址!

#include <stdio.h>
int sort_by_int(const void* e1, const void* e2);
void swap(char* se1, char* se2, size_t wideth);
void bubble_qsort(void* base, size_t count, size_t wideth, int (*cmp)(const void* e1, const void* e2));
int main()
{	
	int arr[10] = { 12,15,20,30,45,5,8,10,4,2 };
	bubble_qsort(arr, 10, sizeof(arr[0]), sort_by_int);
	printf("after sorted: ");
	for (int i = 0; i < 10; i++)
	{
		printf("%d ",arr[i]);
	}
}

void swap(char* se1, char* se2, size_t wideth)
{
	int i = 0;
	for (i = 0; i < wideth; i++)
	{
		char tem = 0;
		tem = *se2;
		*se2 = *se1;
		*se1 = tem;
		se1++;
		se2++;
	}
}

int sort_by_int(const void* e1, const void* e2)
{
	return *((int*)e1) - *((int*)e2);
}

void bubble_qsort(void* base, size_t count, size_t wideth, int (*cmp)(const void* e1, const void* e2))
{
	int i = 0;
	for (i = 0; i < count; i++)
	{
		int j = 0;
		for (j = 0; j < count - i - 1; j++)
		{
			if (cmp((char*)base + j * wideth, (char*)base + (j + 1) * wideth) > 0)
			{
				swap((char*)base + j * wideth, (char*)base + (j + 1) * wideth, wideth);
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值