Gestione liste e file binari - qsort.c
Cerca
 











qsort.c

Caricato da: Bonny
Scarica il programma completo

  1. #include <stdio.h>
  2. #include <string.h>
  3. #define dim 5 //dimensione fisica dell'array
  4.  
  5. //struttura
  6. typedef struct {
  7.         char nome[20];
  8.         char cogn[20];
  9.         int matr;
  10.         }studente;
  11.        
  12. //prototipi
  13. void printarray(studente v[]);
  14. void scanarray(studente v[]);
  15. int compare(studente *, studente *);
  16.  
  17. // main
  18. main(){
  19.        studente stud[dim];//array di tipo studente di 'dim' elementi
  20.        
  21.        scanarray(stud);
  22.        
  23.        printarray(stud);
  24.        
  25.        qsort(stud,dim,sizeof(studente),compare);// ordina l'array
  26.        
  27.        printarray(stud);//stampa array ordinato
  28.        
  29.        system("PAUSE");
  30. }//fine main
  31.        
  32. //procedura per stamapare gli elementi dell'array      
  33. void printarray(studente v[]){
  34.      
  35.      int j;
  36.      printf("\n\n");
  37.      for(j=0;j<dim;j++){
  38.                         printf("%s\t%s\t%d\n\n",v[j].cogn,v[j].nome,v[j].matr);
  39.                         }
  40. }
  41. //procedura inserire elementi nell'array
  42. void scanarray(studente v[]){
  43.      
  44.        int i;
  45.        
  46.        for(i=0;i<dim;i++){
  47.                           system("cls");      
  48.                           printf("Inserire il nome: ");
  49.                           scanf("%s",v[i].nome);
  50.                           printf("\n\nInserire il cognome: ");
  51.                           scanf("%s",v[i].cogn);
  52.                           printf("\n\nInserire il matricola: ");
  53.                           scanf("%d",&v[i].matr);                                                  
  54.                           }
  55. }
  56. //funzione compare elementi della struttura
  57. int compare(studente *e1, studente *e2){
  58.    
  59.     if (strcmp(e1->cogn,e2->cogn)==0)
  60.    
  61.          if (strcmp(e1->nome,e2->nome)==0)
  62.        
  63.              if (e1->matr < e2->matr)
  64.            
  65.                        return -1;
  66.                
  67.              else if (e1->matr>e2->matr)
  68.            
  69.                        return +1;
  70.                
  71.                   else return 0;
  72.            
  73.         else return strcmp(e1->nome,e2->nome);
  74.        
  75.     else return strcmp(e1->cogn,e2->cogn);
  76. }
 

Creative Commons License
Il layout di questo sito è concesso sotto licenza Creative Commons.
Per maggiori informazioni sulle licenze dei contenuti del sito, clicca.