Create function to sort alphabetically

Asked

Viewed 46 times

0

#include <stdio.h>

#include <string.h>

typedef struct s_pessoa{

  char nome[100];

  char matricula[100];

  long int curso;
}
pessoa;

void ordena(pessoa aluno[]){

//aqui é para ordenar o nome por ordem alfabética

 
}




int main(void) {

  pessoa aluno[5];

  int i, n=5;

  for(i=0;i<n;i++){
    printf("Nome do aluno %d \n", (i+1));

    fgets(aluno[i].nome,100,stdin);

    printf("Matricula: \n");

    fgets(aluno[i].matricula,100,stdin);

    printf("Curso:  \n");

    scanf("%ld", &aluno[i].curso);

    getchar();
  }

}
  • Take a look at this answer. Take good care of your problem. https://answall.com/questions/92516/howto sort a-chainedlist

1 answer

1

After working hard, finally I sewed. I haven’t used C++for years, who will say C. Follows the code:

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

// odernar a lista em ordem alfabetica


int main() {
    const char* to_ord[] = { "Joao", "Maria", "Joseh", "Joana", "Joauo", "Pedro", "Miguel", "Anja", "Aboemir" };

    int tam = sizeof(to_ord) / sizeof(char*);
    for (int x = 0; x < tam; ++x) {
        for (int y = x; y < tam; ++y) {
            if (strcmp(to_ord[x], to_ord[y]) == 1) {
                char* old = (char*)to_ord[x];
                to_ord[x] = (char*)to_ord[y];
                to_ord[y] = (char*)old;
            }
        }
    }
    for (int x = 0; x < tam; ++x) {
        printf("%s\n", to_ord[x]);
    }
    
    return 0;
}

Explaining:

  • I use the func strcmp to know which of the 2 strings is "larger alphabetically".
  • Then I only make this comparison for everyone on my list and change if it’s bigger.

To better understand is about the sorting algorithm used, click here. For documentation of strcmp, click here.

Browser other questions tagged

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