機試演算法講解:第2題 結構體之快速排序
阿新 • • 發佈:2019-01-30
/* 題目: 學生成績排序:成績從低到高,姓名字母從低到高(區分大小寫),年齡從低到高排序 輸入: 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; }