Difficulty in sorting

0

I'm doing a program that orders the words, but if they are the same size you can not 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 input Top Coder comp Wedn at midnight

Exit

Midnight Coder comp Wedn Top at

    
asked by anonymous 03.09.2018 / 23:48

1 answer

3

Your problem was in Selection Sort was doing a poor implementation of the algorithm. It should have an extra variable max , because when doing the exchange the name with index i would get lost, I do not know if I'm explaining well. A good method to notice was to see what your sorting code does step by step and discovers its error.

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 is this way, find the minimum / maximum and then change.

Code not ideone

Top Coder comp Wedn at midnight

i = 0- > top ----- j = 1-> Coder (need to make the exchange)

i = 0-> Coder ---- j = 2-> comp

Selection Sort

    
04.09.2018 / 00:10