用qsort 函数优化冒泡排序

在讲解qsort函数之前,我们先来复习一下冒泡排序

#include<stdio.h>
int main()
{
  int i=0,j=0;
  int arr[]={1,2,3,4,5,6,7,8,9,10};
  int sz=sizeof(arr)/sizeof(arr[0]);
  for(i=0;i<sz;i++)
   {
     for(j=0;j<sz-i-1;j++)
        {
             if(arr[j+1]>arr[j])
                 {
                      int temp=arr[j+1];
                      arr[j+1]=arr[j];
                      arr[j]=temp;
                 }
        }
   }
 

}

通过双循环来将整数数组进行排列,相比于传统的将各个数进行比较其大小,但是其缺点也显而易见,那就是传统的冒泡排序只能对整型进行排序,功能十分单一,接下来我们就利用qsort函数的思想来优化代码,使其成为可以排序任意类型的一串代码。

再开始改造之前,我们首先需要了解一下qsort函数

void* qsort(void* base,size_t num,size_t width,int(*cmp)(const void*e1,const void* e2))

第一个参数表示需要排序参数的首地址,第二个参数是排序内容的个数,第三个参数表示字节大小,最后一个参数为一个函数,此函数为一个比较函数,需要我们自己来实现。

char cmp(const void* e1, const void* e2)
{
	return (*(char*)e1 - *(char*)e2);
}

函数的类型由自己来定义,此函数为升序,若要实现降序就讲两参数相互对掉即可。

接下来模拟qsort函数

void my_qsort(void* base, int num, int width, char(*cmp)(const void*e1, const void* e2))
{
	int i = 0;
	char tmp[16];
	for (i = 0; i < num-1; i++)
	{
		int j = 0;
		for (j = 0; j < num - 1 - i; j++)
		{
			if (cmp((char*)base+j*width,(char*)base+(j+1)*width) > 0)
			{
				memcpy(tmp, (char*)base + j * width,width);
				memcpy((char*)base + j * width, (char*)base + (j + 1)*width,width);
				memcpy((char*)base + (j + 1)*width, tmp, width);
			}
		}
	}
}

定义tmp为16个字节是为了防止long double类型,利用memcpy库函数来防止发生其他不必要的麻烦,完整代码如下(以排序字符串为例)

#include<stdio.h>
#include<string.h>
char cmp(const void* e1, const void* e2)
{
	return (*(char*)e1 - *(char*)e2);
}

void my_qsort(void* base, int num, int width, char(*cmp)(const void*e1, const void* e2))
{
	int i = 0;
	char tmp[16];
	for (i = 0; i < num-1; i++)
	{
		int j = 0;
		for (j = 0; j < num - 1 - i; j++)
		{
			if (cmp((char*)base+j*width,(char*)base+(j+1)*width) > 0)
			{
				memcpy(tmp, (char*)base + j * width,width);
				memcpy((char*)base + j * width, (char*)base + (j + 1)*width,width);
				memcpy((char*)base + (j + 1)*width, tmp, width);
			}
		}
	}
}

int main()
{
	char arr[10] = "fedcba";
	int sz = strlen(arr);
	my_qsort(arr,sz,sizeof(char),cmp);
	puts(arr);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抱着太阳吃雪糕z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值