按出发日期对航班进行排序

时间:2018-12-10 06:17:05

标签: c

以下是这些航班:

AA43 DFW DTW 2016-01-06 11:00
AA43 DFW DTW 2016-01-17 11:00
AA44 SEA JFK 2015-02-05 7:45
AA197 ORD BOS 2012-03-12 11:50 
AA1 JFK LAX 2016-07-02 9:00
OO7435 DTW PLN 2016-11-22 21:55
F9612 DEN MIA 2014-12-19 22:15
DL801 GEG MSP 2016-08-31 9:00
DL1087 ATL DAB 2016-04-10 12:05
DL828 IAH SLC 2012-06-02 7:45

现在想象一下所有这些航班是否都在文本文件中。 您如何按出发日期对它们进行排序? 当我指的是“出发日期”时,我的意思是按照“ yyyy-mm-dd hr:min”对它们进行排序。

当我尝试对其进行排序时,它将仅对所有航班进行排序,而不是按起飞日期进行排序。如果没有航空公司的航班,但只有出发日期,那将是完美的选择。

这就是我先前所说的代码中的样子。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE *fp1;
    FILE *fp2;
    int i, j;
    int line = 0;
    char temp[128], outputFile[15], airLine[256];
    char **strData = NULL;

    printf("Enter input file name:");
    scanf("%s", airLine);

    fp1 = fopen(airLine,"r");
    if (!fp1)
    {
       return 1;
    }

    sprintf(outputFile, "sun");
    fp2 = fopen(outputFile, "w");

    while(fgets(temp, 128, fp1))
    {
        if(strchr(temp, '\n'))
        {
            temp[strlen(temp-1)] = '\0';
            strData = (char**)realloc(strData, sizeof(char**)*(line+1));
            strData[line] = (char*)calloc(128, sizeof(char));
            strcpy(strData[line], temp);
            line++;
        }
    }
    for(i= 0; i < (line - 1); ++i)
    {
        for(j = 0; j < ( line - i - 1); ++j)
        {
            if(strcmp(strData[j], strData[j+1]) > 0)
            {
                strcpy(temp, strData[j]);
                strcpy(strData[j], strData[j+1]);
                strcpy(strData[j+1], temp);
            }
        }
    }
    for(i = 0; i < line; i++)
    {
        fprintf(fp2,"%s\n",strData[i]);
    }
    for(i = 0; i < line; i++)
    {
        free(strData[i]);
    }
    free(strData);
    fclose(fp1);
    fclose(fp2);
    return 0;
} 

如何按出发日期对上面列出的航班进行排序?

1 个答案:

答案 0 :(得分:2)

这需要一些努力。

  1. 定义航班数据的结构

    struct flight {
      char flight_no[10];
      char takeoff[4];
      char landing[4];
      // you can convert string to tm using
      // strptime (take a look at time.h)
      struct tm *date_and_time;
    };
    
  2. 通过存储指向结构的指针来创建元素表

  3. 创建可以按日期比较元素的函数(请参见man qsort

    int (*compar)(const void *, const void *)
    

    进行比较的函数带有两个参数(由void *指向)。我们要做的(在它里面)就是将void *转换为我们要处理的类型的指针并比较值。

    int
    compare_doubles (const void *a, const void *b)
    {
      const double *da = (const double *) a;
      const double *db = (const double *) b;
    
      if(*da > *db) {
        return 1;
      } else if(*da < *db) {
        return -1;
      } else {
        return 0;
      }
    }
    

    来源:http://www.gnu.org/software/libc/manual/html_node/Comparison-Functions.html

    请注意这部分文档

      

    您的比较函数应以strcmp的方式返回一个值:   如果第一个参数“小于”第二个参数,则为负;如果第一个参数小于第二个参数,则为零   是“等于”,如果第一个参数是“更大”,则为正。

  4. 使用qsort

    对元素进行排序
    man qsort