/* 题目: 学生成绩排序:成绩从低到高,姓名字母从低到高(区分大小写),年龄从低到高排序 输入: 3 abc 20 99 bcd 19 97 bed 20 97 输出: bcd 19 97 bed 20 97 abc 20 99 易错点: 1对于字符指针,scanf("%s",ps[i].sName)不需要取地址符 2对于名字,要指定大小,否则内存访问非法,char sName[128];而不是定义char* sName; 3int strcmp(const char* string1,const char* string2); <0:前<后 得分:0 */ #include <stdio.h> #include <malloc.h> #include <string.h> typedef struct Student { //Student(char* name,int age,int grade):sName(name),iAge(age),iGrade(grade){} //char* sName;//就是这里出错了,没有具体制定多大 //char* sName; //法二,用重载操作符operator<的方法做 bool operator < (const Student& stu) const { if(iGrade != stu.iGrade) { return iGrade < stu.iGrade; } else { if(sName != stu.sName) { return strcmp(sName,stu.sName) < 0 ? true:false; } else { return iAge < stu.iAge; } } } char sName[128]; int iAge; int iGrade; }Student; bool compare(struct Student stuA,struct Student stuB) { if(stuA.iGrade < stuB.iGrade) { return true; } else if(stuA.iGrade == stuB.iGrade ) { if(stuA.sName!=stuB.sName) { return strcmp(stuA.sName,stuB.sName) < 0 ? true:false ;//这里中断了 } else { return stuA.iAge < stuB.iAge; } } else { return false; } } int partition(Student* ps,int low,int high) { Student stu = ps[low]; while(low < high) { //while(low < high && compare(stu,ps[high]))//法1 while(low < high && stu < ps[high]) { high--; } ps[low] = ps[high]; //while(low < high && compare(ps[low],stu))//法1 while(low < high && ps[low] < stu) { low++; } ps[high] = ps[low]; } ps[low] = stu; return low; } void quickSort(Student* ps,int low,int high) { if(low < high) { int iPos = partition(ps,low,high); quickSort(ps,low,iPos-1); quickSort(ps,iPos+1,high); } } void print(Student* ps,int iNum) { for(int i = 0;i < iNum ;i++) { printf("%s %d %d\n",ps[i].sName,ps[i].iAge,ps[i].iGrade); } } int main(int argc,char* argv[]) { int iNum; while(EOF!=scanf("%d",&iNum)) { //ptrStu ps = (ptrStu)malloc(iNum*sizeof(Student)); Student* ps = (Student*)malloc(iNum*sizeof(Student)); //Student ps[100]; for(int i = 0; i < iNum; i++) { //char* sName; //int iAge,iGrade; //scanf("%s %d %d",&ps[i].sName,&ps[i].iAge,&ps[i].iGrade); //关键字符串不需要取地址,因为它本身就是一个地址,否则就是取地址的地址了 scanf("%s %d %d",ps[i].sName,&ps[i].iAge,&ps[i].iGrade); //Student *stu = (Student*)malloc(1*sizeof(Student))(sName,iAge,iGrade); //ps[i] = stu;//难道是因为出了这里就不存在了 } //printf("%s\n",ps[1].sName); //print(ps,iNum); quickSort(ps,0,iNum-1); print(ps,iNum); free(ps); } //getchar(); return 0; }