简体   繁体   中英

Why doesn't this sorting function work? C

So I have this sorting function that is suppose to take in an array of structs and I need to organize them by name, both have a first and last name and if their last names are the same then I must move on to the first name to compare as well. So I made 2 strings that contain the last and first name combined into 1, and I iterate through the list and see which is small and move it up. But the issue is...it doesnt do anything...at all, and I don't understand why!?

void sortStruct(struct student *list, int studentCount){

int j, k;

struct student temp;

char buffer[35];
char buffer2[35];

for (j = 0 ; j <= studentCount-2 ; j++){

    sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);

    for(k = 1 ; k <= studentCount-1 ; k++){

        sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);

        if(buffer < buffer2){

            temp = list[j];
            list[j] = list[k];
            list[j] = temp;

        }
    }
}
}

Anyone know whats wrong?

buffer < buffer2 is absolutely not what you want. That's just comparing two memory addresses! You should use the function strcmp() . For example,

if (strcmp(buffer, buffer2) < 0)

Your function should be like below:

For Name Comparison

void sortStruct(struct student *list, int studentCount)
{

   int j, k;
   struct student temp;
   char buffer[35];
   char buffer2[35];

   for (j = 0 ; j <= studentCount-2 ; j++)
   {
     sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);
     for(k = 1 ; k <= studentCount-1 ; k++)
     {
       sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);
       if(strcmp(buffer, buffer2)<0)
       {
            temp = list[j];
            list[j] = list[k];
            list[j] = temp;
       }
     }
   }
}

For Name Length Comparison

void sortStruct(struct student *list, int studentCount)
{

  int j, k;
  struct student temp;
  char buffer[35];
  char buffer2[35];

  for (j = 0 ; j <= studentCount-2 ; j++)
  {
    sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);

    for(k = 1 ; k <= studentCount-1 ; k++)
    {

     sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);

      if(strlen(buffer)< strlen(buffer2))
      {
         temp = list[j];
         list[j] = list[k];
         list[j] = temp;
      }
    }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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