编写函数,将一组(n个)日期(字符串),按日期从小到大(由远及近)排序。 函数接口定义: void datesort ( char d[][11], int n ); 其中字符型二维数组 d 中存放了 n 个日期,数组 d 的每一行存放一个日期,格式为:MM/DD/YYYY。 裁判测试程序样例: #include <stdio.h> #include <string.h> void datesort ( char d[][11], int n ); int main() { char date[80][11]; int n,i; scanf("%d",&n); for(i=0;i<n;i++) scanf("%s",date[i]); datesort(date,n); for(i=0;i<n;i++) puts(date[i]); return 0; } /* 请在这里填写答案 */
时间: 2024-03-23 09:39:15 浏览: 54
答案如下:
```c
#include <stdio.h>
#include <string.h>
void datesort(char d[][11], int n) {
int i, j;
char temp[11];
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
int year1, month1, day1;
sscanf(d[i], "%d/%d/%d", &month1, &day1, &year1);
int year2, month2, day2;
sscanf(d[j], "%d/%d/%d", &month2, &day2, &year2);
if (year1 > year2 || (year1 == year2 && (month1 > month2 || (month1 == month2 && day1 > day2)))){
strcpy(temp, d[i]);
strcpy(d[i], d[j]);
strcpy(d[j], temp);
}
}
}
}
```
这个函数的思路是使用选择排序法,遍历每一对日期,比较它们的大小,如果前者比后者大,则交换两个日期的位置。
在比较过程中需要先将日期字符串按照年、月、日的顺序解析成整数形式,然后再比较它们的大小。可以使用 `sscanf()` 函数将日期字符串解析成整数。
阅读全文
相关推荐
















