sorting - How to sort data 2 times simultaneously in C/C++ -
i want sort data of file 2 times :
- according weather,
- according day.
now here's crunch : want sort data first weather, , keep static(constant) & sort according day.
example : data file contains :
sunday humid wednesday hot friday rainy saturday dry monday wet tuesday dry thursday cloudy
so after dual sorting looks :
thursday cloudy tuesday dry saturday dry wednesday hot sunday humid friday rainy monday wet
i have tried many things, , nothing worked ~sighs~ have been busy on 12-15 days :/
i'm working in c language, & here's code :
#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 %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); { ch=0; (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); (i = 0; < n; i++) { fprintf(ft,"\n %s \t %s",record[i].day,record[i].weather); } fclose(fp); fclose(ft); return 0; }
this extremely trivial, write comparator compares weather, , if that's equal, compares day instead:
int compare(s *a, s* b) { int res = strcmp(a->weather, b->weather); return res==0 ? strcmp(a->day, b->day) : res; }
this can't have possibly taken two weeks.
Comments
Post a Comment