Print strings in alphabetical order

2

I'm trying to do here because the user provides 3 names at least so I have to sort those names alphabetically, I had tried with strcmp , but I did not quite understand the concept of this command. So I used the following code:

char nm1[20], nm2[20], nm3[20], cont;
        char alf[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','w','y','z'};
        char alfb[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','W','Y','Z'};
        printf("Nome 1: ");
        scanf("%s", &nm1);
        printf("Nome 2: ");
        scanf("%s", &nm2);
        printf("Nome 3: ");
        scanf("%s", &nm3);

        for(cont = 0; cont < 26; cont++){
            if(nm1[0] == alf[cont]|| nm1[0] == alfb[cont])
                printf("- %s", nm1);
            if(nm2[0] == alf[cont]|| nm2[0] == alfb[cont])
                printf("- %s", nm2);
            if(nm3[0] == alf[cont]|| nm3[0] == alfb[cont])
                printf("- %s", nm3);    
        }

He compares the first letter of each name and print if it equals the letter they are reading from the alphabet. But so it only orders by the first letter of the name, if the user type ana, andre e adão it will print in the same order and not in the correct alphabetical order

    
asked by anonymous 02.07.2015 / 19:14

4 answers

4

The strcmp() function gets two strings to be compared and will have 3 possible returns:

  • less than 0 : When you find a different character in strings and this character of the first String is smaller than the second String character. (before)

  • equal to 0 : when they are equal.

  • greater than 0 : When you find a different character in the strings and that character of the first String is greater than the second String . (after)

I suggest that you change your three variables to an array of char , so it will be very simple to sort.

char nm[3][20], aux[20];

for (i = 0; i < 3; i++) {
   printf("\nNome %i: ", i+1);
   scanf("%s", nm[i]);
}


for (i = 1; i < 3; i++) { /* 3 = qtde de palavras */
   for (j = 1; j < 3; j++) {
      // verifica se tem que ser depois, se for troca de posição
      if (strcmp(nm[j - 1], nm[j]) > 0) {
         strcpy(aux, nm[j - 1]);
         strcpy(nm[j - 1], nm[j]);
         strcpy(nm[j], aux);
      }
   }
}

// só mostrar a matriz
for (i = 0; i < 3; i++)
   printf("\n%s", nm[i]);

Remember to give include in <string.h> .

    
02.07.2015 / 19:39
2

I'll post a possible answer, it's a simple algorithm that does word sorting using selectSort, qtd is the number of words and tam is the size of words.

# include<stdio.h>
const int qtd = 10;
const int tam = 30;
main()
{
    int i, j, x, menor;
    char a[qtd][tam], aux[qtd];
    for(i = 0; i < qtd; i++)
    {
        printf("Informe o %d° nome: ", i + 1);
        scanf("%s", a[i]);
    }
        for(i = 0; i < qtd - 1; i++)
        {
                x = 0;
                menor = i;
                for(j = i + 1; j < qtd; j++)
                {
                    x = 0;
                    while(a[menor][x] == a[j][x])
                    {
                            x++;
                    } 
                    if(a[menor][x] > a[j][x])
                    {
                         menor = j;
                    }
                }
                if(menor != i)
                {
                        strcpy(aux, a[menor]);
                        strcpy(a[menor], a[i]);
                        strcpy(a[i], aux);
                }
        }
        for(i = 0; i < qtd; i++)
        {
                printf("%s%c", a[i], 10);
        }
}
    
02.07.2015 / 19:41
2

The strcmp() returns one of three options.

cmp = strcmp(n1, n2);
if (cmp == 0) /* n1 igual a n2 */;
if (cmp < 0) /* n1 menor que n2 */;
if (cmp > 0) /* n1 maior que n2 */;

As long as you remember this, the use of strcmp is nothing special.

To compare names, you have to convert everything to lowercase (or uppercase) before the comparison: a cycle with tolower() solves this problem.

In pseudo code

obter nm1, nm2, nm3
converter nm1, nm2, e nm3 para minusculas,
      possivelmente com copia para nao perder a informacao original
trocar nm1 e nm2?
trocar nm2 e nm3?
trocer nm1 e nm2?
imprimir (as copias originais de) nm1, nm2, e nm3
    
02.07.2015 / 19:42
0
/* Ordenar vetor alfabeticamente*/

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

int main (){

char nome[3][100], copia[100];

int i, j;

/* A variável nome armazena 3 nomes com até 100 caracteres.

A variável copia é apenas uma auxiliar que recebe 100 caracteres
*/

//Entrada dos nomes

for ( i = 0; i < 3; i ++){
   printf ( "Informe o nome: " );
   gets ( nome[i] );
}

//A troca alfabeticamente

for ( i = 0; i < (3-1) ; i ++ ) 
   for( j = i + 1; j < 3; j ++ )

/* strcmp 
     retorna = 0, caso a = b
     retorna > 0, caso a > b
     retorna < 0, caso a < b
*/

      if ( strcmp( nome[i], nome[j] ) > 0 ){
/* strcpy
       copia de string 
       strcpy ( VarRecebe, VarEntrega )
*/
          strcpy ( copia, nome[i] );
         strcpy( nome[i], nome[j] );
         strvpy( nome[j], copia) ;
}


/* Apresentação do vetor

Essa eu deixo para que finalizes, ou seja para que a gente não faça tudo. 
Acredito que sabes a lógica para apresentar um determinado vetor, portanto só tens de colocá-la abaixo . 

NB: Considerando que o vetor é nome[] e não nome[][]
*/


}
}
    
05.10.2016 / 10:40