机试算法讲解:第2题 结构体之快速排序
2015-07-30 23:15
429 查看
/* 题目: 学生成绩排序:成绩从低到高,姓名字母从低到高(区分大小写),年龄从低到高排序 输入: 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; }
相关文章推荐
- 大数据系列修炼-Scala课程06
- 微信OAuth2网页授权获取用户信息
- 实战 oracle 函数小结
- 支持向量机通俗导论(理解SVM的三层境界)
- vim乱码问题
- Tomcat 定制JNDI URL Resource
- Ubuntu上安装 Emacs 24的几种方法
- roman to integer
- 一步步完全解析AsyncTask
- dom 笔记
- UIMenuController—为UILabel添加UIMenuController
- 蟠桃会之教育、投资与幸福生活
- 微信JS接口
- 程序员,为什么千万不要重写代码?
- Java Collection框架—List\ set \map 的异同世界
- 泛型依赖注入
- 《深入理解Nginx 模块开发与架构解析》笔记之epoll事件模块
- 机试算法讲解:第1题 冒泡排序与快速排序
- AutoRunner note
- GameUnity 2.0 文档(一) 事件机制