简体   繁体   English

如何将结构成员与冒泡排序保持在一起?

[英]How can I keep members of a struct together with bubble sort?

I've created a list of names in a .csv file, and I am trying to sort them alphabetically. 我已经在.csv文件中创建了一个名称列表,并且尝试按字母顺序对它们进行排序。 Right now I've got an array of structs. 现在,我有一系列的结构。 The struct only has 2 members, the first and last name. 该结构只有2个成员,名字和姓氏。 I've got my bubble sort to sort based on first name which is what I want, but how can I keep the last name with them? 我已经根据想要的名字对泡沫排序进行了排序,但是如何保留姓氏呢? When I print the array back out the last names do not line up with the first name. 当我打印出数组时,姓氏不与名字对齐。

void bubbleSort(cred name[], int n) { 

  char temp[25];
  int i,j;

  for(i=1;i<=n;i++)
    for(j=0;j<=n-i;j++)
      if(strcmp(name[j].first,name[j+1].first)>0)
      { 
        strcpy(temp,name[j].first);
        strcpy(name[j].first,name[j+1].first);
        strcpy(name[j+1].first,temp);
      }

   printf("The strings appears after sorting :\n");
   for(i=0;i<=n;i++)
     printf("%s  %s\n",name[i].first,name[i].last);
}

I think your logic appears sound, someone is free to correct me, but you should also swap your last names whenever you swap the first names. 我认为您的逻辑听起来不错,有人可以自由地纠正我,但是每当交换名字时,也应该交换姓氏。

You could also just create a temp of type cred swap the previous element of the array with the next, both of type cred. 您也可以创建一个cred类型的临时文件,将数组的前一个元素与下一个类型均为cred的元素交换。

Simply replace 只需更换

    strcpy(temp,name[j].first);
    strcpy(name[j].first,name[j+1].first);
    strcpy(name[j+1].first,temp);

with

    cred t = name[j];
    name[j] = name[j+1];
    name[j+1] = t;

as structs can be assigned to each other there is no need for copying member by member. 由于结构可以相互分配,因此无需逐个复制成员。

Also notice that all your for loops uses <= - like: 还要注意,所有的for循环都使用<= -如:

for(i=1;i<=n;i++)
         ^^
         here

That seems to be a mistake as n probably represents the number of elements in the array. 这似乎是一个错误,因为n可能代表数组中元素的数量。 So your code is indexing out of bounds. 因此,您的代码超出了索引范围。

So change all your for loops to use < instead of <= 因此,将所有for循环更改为使用<代替<=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM