Difficulty in ordering

Asked

Viewed 75 times

0

I’m doing a program that sorts the words, only if they’re the same size you can’t change places, I’m stuck in that part, the code I already have

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

void coloca(char nomes[][100], char *frase, int *tam);
void ordena(char nomes[][100], int tam);
int main(int argc, char** argv)
{
  char nomes[100][100], frase[2501];
  int tam, i, teste;
  scanf("%d", &teste);
  getchar();
  while(teste--)
  {
     tam = 0;
     scanf("%[^\n]", frase);
     coloca(nomes, frase, &tam);
     ordena(nomes, tam);
     printf("%s", nomes[0]);
     for(i = 1; i < tam; i++)
     {
         printf(" %s", nomes[i]);
     }
     printf("\n");
     getchar();
  }
   return 0;
}

void coloca(char nomes[][100], char *frase, int *tam)
{
   char *ptr = strtok(frase, " ");
   while(ptr != NULL)
   {
       strcpy(nomes[(*tam)++], ptr);
       ptr = strtok(NULL, " ");
    }
 }

 void ordena(char nomes[][100], int tam)
 {
    int i, j;
    char aux[100];
    for(i = 0; i < tam; i++)
    {
       for(j = i + 1; j < tam; j++)
       {
           if(strlen(nomes[i]) == strlen(nomes[j]))
           {

           }
           else if(strlen(nomes[i]) < strlen(nomes[j]))
           {
              strcpy(aux, nomes[i]);
              strcpy(nomes[i], nomes[j]);
              strcpy(nomes[j], aux);
          }
    }
  }
}

Example entree Top Coder comp Wedn at Midnight

Exit

Midnight Coder comp Wedn Top at

  • Can you give more examples ? So if all strings have the same size nothing is changed ?

1 answer

3

His problem was in the Selection Sort was doing a bad algorithm implementation. You must have an extra variable max, because when trading the name with index i I don’t know if I’m explaining it right. A good method to realize was to see what your sorting code does step by step and discover your mistake.

void ordena(char nomes[][100], int tam)
{
    int i, j, max;
    char aux[100];
    for(i = 0; i < tam-1; i++)
    {
        max=i;
        for(j = i + 1; j < tam; j++)
        {
            if(strlen(nomes[j]) > strlen(nomes[max]))
                max=j;
        }
        strcpy(aux, nomes[i]);
        strcpy(nomes[i], nomes[max]);
        strcpy(nomes[max], aux);
    }
}

Selection Sort looks like this, finds the minimum/maximum and then switches.

Code in the ideone


Top Coder comp Wedn at midnight

i=0-> top-----j=1->Coder (it is necessary to make the exchange)

i=0->Coder----j=2->comp <- You’re going to miss the test i original, which will originate in a bad ordination by the method selection sort


Selection Sort

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.