使用VC库函数中的快速排序函数

上一篇讲了快速排序的实现。但在很多场合,直接使用快速排序的库函数是很方便的。下面讲下VC中库函数qsort()的用法:http://blog.csdn.net/morewindows/article/details/6684561

函数原型:

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

第一个是数组地址,第二是数组大小,第三个是数组中每个元素的字节数,最后一个是个函数指针,表示如何比较数组中的元素。

头文件 #include <stdlib.h>

下面分别就int等整数数据,double等浮点数据,结构体和类,按指定方式这四种情况进行讲解。

实例1   对int等整数数据进行排序

int cmp(const void *x, const void *y)
{
	return *(int*)x - *(int*)y;
}
qsort(a, MAXN, sizeof(a[0]), cmp); 

MAXN为数组大小,下同

实例2   对double等浮点数进行排序

 

MAXN为数组大小,下同

实例2   对double等浮点数进行排序

int cmpDouble(const void *x, const void *y)
{
	return (*(double*)x > *(double*)y ? 1 : -1);
}
qsort(a, n, sizeof(a[0]), cmpDouble);


 

实例3  对结构体,类等复杂数据进行排序

struct Student
{
	char szName[30];
	int  nAge;
};


先对年龄排序,年龄相同再按姓名排序。

int cmpStudent (const void *x, const void *y)
{   //先作下指针转换,再按要求比较
	Student *pNodex = (Student*)x, *pNodey = (Student*)y;
	if (pNodex->nAge != pNodey->nAge)
		return pNodex->nAge - pNodey->nAge;
	else
		return strcmp(pNodex->szName, pNodey->szName);
}
qsort(a, n, sizeof(a[0]), cmpStudent);


 

实例4     按指定方式进行排序。

如对只有大小写字母的字符串"AajkuKdYUBCDwyz"进行排序,要求大写字母在前,小写字母在后。

int cmp1(const void *x, const void *y)
{
	char *pcx = (char*)x, *pcy = (char*)y;

	bool flag1 = *pcx >= 'A' && *pcx <= 'Z';
	bool flag2 = *pcy >= 'A' && *pcy <= 'Z';

	if(flag1 == flag2)    //如果都为大写字母或都为小写字母
		return *pcx - *pcy;
	else                  //否则,谁为大写字母,谁的权值小。
		return flag1 ? -1 : 1;
}
int main()
{
	char szText[] = "AajkuKdYUBCDwyz";
	qsort(szText, strlen(szText), sizeof(szText[0]), cmp1);
	printf("%s\n", szText);
	return 0;
}


 

 

完整的代码如下:

int cmp(const void* x,const void* y)
{
	return *(int*)x-*(int*)y;
}
int cmp1(const void* x,const void* y)
{
	return *(double*)x>*(double*)y?1:-1;
}
struct Student
{
	char szName[30];
	int nAge;
};//字节对齐 占用了36个字节 struct Student Stu[10]; sizeof(Stu)共占用36*10个字节
int cmp2(const void* x,const void* y)
{
	Student* pNodex=(Student*)x,*pNodey=(Student*)y;
	if(pNodex->nAge!=pNodey->nAge)
		return pNodex->nAge-pNodey->nAge;
	else
		return strcmp(pNodex->szName,pNodey->szName);
}
int main(void)
{
	struct Student Stu[10];
	for(int i=0;i<10;i++)
	{
		Stu[i].nAge=i;
		strcpy(Stu[i].szName,"miao");
	}
	swap(Stu[0],Stu[3]);
	strcpy(Stu[4].szName,"abc");
	cout<<sizeof(Stu)<<endl;
	cout<<sizeof(struct Student)<<endl;
	qsort(Stu,10,sizeof(struct Student),cmp2);
	for(int i=0;i<10;i++)
	{
		cout<<Stu[i].szName<<" "<<Stu[i].nAge<<endl;
	}
	cout<<endl;
}


 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值