Advertisement
Guest User

Ordinamento Array c

a guest
Dec 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <time.h>
  5.  
  6.  
  7. void stampa(int vett[], int lunghezza)
  8. {
  9.     int i;
  10.     for(i=0; i<lunghezza; i++)
  11.     {
  12.         printf("%d ", vett[i]);
  13.     }
  14.     printf("\n");
  15. }
  16. //https://italiancoders.it/ordinamento-di-un-array-parte-1/
  17. void selectionSort(int vett[], int lunghezza)
  18. {
  19.     int i, j;
  20.     for(i=0; i<lunghezza-1; i++)
  21.     {
  22.         for(j=i+1; j<lunghezza; j++)
  23.         {
  24.             if(vett[i] > vett[j])
  25.             {
  26.                 int temp = vett[i];
  27.                 vett[i]=vett[j];
  28.                 vett[j]=temp;
  29.             }
  30.         }
  31.     }
  32. }
  33. //https://italiancoders.it/ordinamento-di-un-array-parte-1/
  34. void bubbleSort(int vett[], int lunghezza)
  35. {
  36.     bool scambio;
  37.     int i,j;
  38.  
  39.     for(i=0; i<lunghezza; i++)
  40.     {
  41.         scambio = false;
  42.         for(j=1; j<lunghezza-1 && scambio==false; j++)
  43.         {
  44.             if(vett[j-1] > vett[j])
  45.             {
  46.                 int temp = vett[j-1];
  47.                 vett[j-1]=vett[j];
  48.                 vett[j]=temp;
  49.                 scambio = true;
  50.             }
  51.         }
  52.     }
  53. }
  54.  
  55. int main()
  56. {
  57.     clock_t start, end;
  58.     int l = 100000;
  59.     int a[l];
  60.     srand(time(NULL));
  61.     int i;
  62.     for(i=0; i<l; i++)
  63.     {
  64.         a[i] = (rand() % l*2) + 1;
  65.     }
  66.     //stampa(a,l);
  67.     start = clock();
  68.  
  69.     //Ti ho messo 2 algoritmi di ordinamento base.
  70.     //Prova a far partire il programma prima commentando il metodo bubbleSort, così verrà eseguito il selectionSort
  71.     //noterai che su un'array di 100.000 elementi il tempo di esecuzione stampato sarà molto grande.
  72.     //Ora commenta il selectionSort, e riesegui il programma, noterai un'incremento significativo del tempo di esecuzione.
  73.     //Sopra ai 2 metodi ti ho lasciato un sito dove ti fa vedere anche con una animazione come funzionano i 2 algoritmi
  74.  
  75.     selectionSort(a,l);
  76.     //bubbleSort(a,l);
  77.  
  78.     end = clock();
  79.     double tempoImpiegato = (double)(end - start) / (double)CLOCKS_PER_SEC;
  80.     printf("Tempo impiegato per eseguire un ordinamento: %lf secondi\n",tempoImpiegato);
  81.     //stampa(a,l);
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement