PTA 7-241 按日期排序
分数 10
作者 ZJUTOJ
单位 绍兴文理学院
输入若干日期,按日期从小到大排序。
输入格式:
本题只有一组测试数据,且日期总数不超过100个。按“MM/DD/YYYY”的格式逐行输入若干日期。
输出格式:
按“MM/DD/YYYY”的格式输出已从小到大排序的各个日期,每个日期占一行。
输入样例:
12/31/2005
10/21/2003
02/12/2004
11/12/1999
10/22/2003
11/30/2005
输出样例:
11/12/1999
10/21/2003
10/22/2003
02/12/2004
11/30/2005
12/31/2005
出处:
ZJUTOJ 1045
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <stdio.h>
struct Date { //定义结构体
int month; //月份
int day; //日期
int year; //年份
};
void swap(struct Date *a, struct Date *b) { //交换值
struct Date temp = *a;
*a = *b;
*b = temp;
}
int compareDates(struct Date date1, struct Date date2){ //比较相邻的数据
if(date1.year != date2.year){ //相邻年份不相等
return date1.year - date2.year;
}else if (date1.month != date2.month){ //相邻年份相等, 相邻月份不相等
return date1.month - date2.month;
}else{ //相邻年份和月份都相等
return date1.day - date2.day;
}
}
void sortDates(struct Date dates[], int n) { //排序
int i, j;
for(i = 0; i < n-1; i++){
for(j = 0; j < n-i-1; j++){
if(compareDates(dates[j], dates[j+1]) > 0){ //相邻的数据返回值为正(因为, 如果为负就不需要交换值)
swap(&dates[j], &dates[j+1]);
}
}
}
}
int main() {
struct Date dates[100];
int n = 0; //日期总数
// 逐行输入日期数据
while(~scanf("%d/%d/%d", &dates[n].month, &dates[n].day, &dates[n].year)){ //处理到文件尾
n++;
}
sortDates(dates, n); //调用函数
for(int i = 0; i < n; i++){ //按照格式输出数据
if(i == n - 1){ //最后一行不输入换行
printf("%02d/%02d/%04d", dates[i].month, dates[i].day, dates[i].year);
break;
}
printf("%02d/%02d/%04d\n", dates[i].month, dates[i].day, dates[i].year);
}
return 0;
}
解题思路:
step1:定义结构体储存数据
step2:将数据按照条件排序
step3:判断相邻的数据,先判断年份,再判断月份,最后判断日期
step4:将判断的值返回,满足条件就将相邻的数据交换
step5:输出结构体储存的数据
归属知识点:
结构体
指针
数组
循环结构
条件判断