如何在C / C ++中同时对数据进行2次排序

时间:2015-05-31 05:59:21

标签: c sorting

我想对我的文件数据进行2次排序:

  1. 根据天气情况,
  2. 根据当天。
  3. 现在是危机:  我想先根据天气对数据进行排序,然后保持静态(恒定)&按照日期排序。

    示例: 我的数据文件包含:

    Sunday Humid
    
    Wednesday Hot
    
    Friday Rainy
    
    Saturday Dry
    
    Monday Wet
    
    Tuesday Dry
    
    Thursday Cloudy
    

    所以经过双重排序后,它看起来像这样:

    Thursday Cloudy
    
    Tuesday Dry
    
    Saturday Dry
    
    Wednesday Hot
    
    Sunday Humid
    
    Friday Rainy
    
    Monday Wet
    

    我尝试了很多东西,没有任何效果〜叹息〜 一直忙于这个12-15天:/

    我在C语言工作,&这是我的代码:

    #include<stdio.h>
    #include<string.h>
    
    int main(){
               typedef struct {
                               char day[10], weather[10];
                              } daydata;
    
    daydata record[30],temp;
    FILE *fp,*ft;
    char line[121];
    
    char *item;
    int reccount =0, k, i, j, n=0,ch;
    
    
    fp = fopen("we.txt","r");
    
    while(fgets(line,120,fp))
    {
    
        item = strtok(NULL," ");
        strcpy(record[reccount].day,item);
    
        item = strtok(NULL,"\n");
        strcpy(record[reccount].weather,item);
    
        printf("%s\n",record[reccount].day);
        reccount++;
    }
    
    fclose(fp);
    
    printf("Weather Record \n\n");
    for(k=0;k<reccount;k++)
    {
    printf("It is %s\n",record[k].weather);
    }
    
        fp = fopen("we.txt","r");
        ft = fopen("sort.txt","w");
    
        while(fgets(lyne,120,fp) != NULL)
                {
                    n++;
                }
    
        for(i=0;i<n;i++)
            fscanf(fp,"%s%s",record[i].day,record[i].weather);
    
        do {
        ch=0;
        for (j=0; j<n-1; j++){
            if (strcmp(record[j].weather, record[j + 1].weather) > 0) {
            temp = record[j];
            record[j] = record[j + 1];
            record[j + 1] = temp;
                ch=1;
            }
    
        }
    } while (ch); 
    
     for (i = 0; i < n; i++) {
      fprintf(ft,"\n %s \t %s",record[i].day,record[i].weather);
    }
    
    fclose(fp);
    fclose(ft);
    
    return 0;
    }
    

1 个答案:

答案 0 :(得分:2)

这非常简单,只需写一个比较天气的比较器,如果相等,则比较一天:

int compare(S *a, S* b)
{
  int res = strcmp(a->weather, b->weather);
  return res==0 ? strcmp(a->day, b->day) : res; 
}

这可能会花费你两周