qsort实现结构体数组排序


要注意强制转换

#include <stdio.h>
#include <stdlib.h>

typedef struct{
	int num;
	char name[20];
	float chinese;
	float math;
	float english;
}Stu,*pStu;
#define N 3
void arrPrint(pStu sArr)
{
	int i;
	for(i=0;i<N;i++)
	{
		printf("%d %10s %5.2f %5.2f %5.2f\n",sArr[i].num,sArr[i].name,sArr[i].chinese,sArr[i].math,sArr[i].english);
	}
}
int compare(const void* pleft,const void* pright)
{
	pStu p1=(pStu)pleft;
	pStu p2=(pStu)pright;
	if(p1->chinese>p2->chinese)
	{
		return 1;
	}else if(p1->chinese<p2->chinese)
	{
		return -1;
	}else{
		return 0;
	}
}
int main()
{
	Stu sArr[N];
	int i;
	for(i=0;i<N;i++)
	{
		scanf("%d%s%f%f%f",&sArr[i].num,sArr[i].name,&sArr[i].chinese,&sArr[i].math,&sArr[i].english);
	}
	printf("----------------------------\n");
	arrPrint(sArr);
	qsort(sArr,N,sizeof(Stu),compare);
	printf("----------------------------\n");
	arrPrint(sArr);
	system("pause");
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM