C语言的比较库函数--qsort

c语言中的库函数:qsort(int *base,int num,int width,int (*compare)(int *void,int *void));

其中base是排序的一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。

比如:对一个长为1000的数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。

qsort(a,1000,sizeof(int),comp);
其中comp函数应写为:
1
2
3
4
intcomp(constvoid*a,constvoid*b)
{
return *( int *)a-*( int *)b;
}
上面是由小到大排序,return *(int *)b - *(int *)a; 为由大到小排序。
举一个例子:对一个结构体中的分数进行排序,结构体的成绩是随机数生成的,学生学号和姓名是从控制台输入的。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/*
测试数据:
001 zhang
002 zhao
003 masan
004 zhaoyun
005 wangqi
006 zhaodan
007 maowanli
008 zhengping
009 bingbing
010 zhahao
*/


struct StuInfo
{
	char sno[20];
	char name[20];
	float score;
};

int p(const void *left, const void *right)
{
	struct StuInfo *stu1 = (struct StuInfo *)left;
	struct StuInfo *stu2 = (struct StuInfo *)right;

	if (stu1->score > stu2->score){
		return -1;
	}
	else{
		return 1;
	}
}



void structSort()
{
	struct StuInfo stu[10], temp;
	srand(time(NULL));
	int i = 0, j = 0, k = 0;
	printf("Please input 10 students' infomation(sno,name):\n");
	for (i = 0; i < 10; ++i){
		scanf("%s %s",stu[i].sno,stu[i].name);
		stu[i].score = rand()%200/2.0;
	}

	/*库函数排序*/
	qsort(stu, 10, sizeof(struct StuInfo), p);
	printf("The student infomation from high to low.\n");
	for (i = 0; i < 10; ++i)
		printf("%5s,%10s,%5.2f\n",stu[i].sno,stu[i].name,stu[i].score);
}

int main()
{
	structSort();
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值