ITAsimo456

Ordine alfabetico

Mar 20th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include<iostream>
  2. #include <string.h>
  3. using namespace std;
  4.  
  5. const int STR_LEN = 25;
  6.  
  7.  
  8. // Restituisce true se str1 e' dopo str2 nell'ordine alfabetico.
  9. // Nota che non fa differenza tra lettere e altri caratteri, e si basa sulla tabella ASCII.
  10. bool alfabetico_dopo(char str1[], char str2[]) {
  11.     int i;
  12.     for (i = 0; str1[i] != '\0' && str2[i] != '\0'; i++) {
  13.         if(str1[i] > str2[i])
  14.             return true;
  15.         else if (str1[i] < str2[i])
  16.             return false;
  17.     }
  18.  
  19.     // Restituisco vero se str1 e' piu' lunga di str2.
  20.     // Esempio: francescoabcd e francesco, la prima e' dopo la seconda in ordine alfabetico.
  21.     return str1[i] != '\0';
  22.  
  23.     // Oppure restituisco semplicemente false, dipende dall'idea.
  24.     // return false;
  25. }
  26.  
  27. // Copia la stringa src in dst.
  28. void copia_stringa(char src[], char dst[]) {
  29.     int i;
  30.     for(i = 0; src[i] != '\0'; i++)
  31.         dst[i] = src[i];
  32.  
  33.     dst[i] = '\0';
  34. }
  35.  
  36. // Scambia due stringhe.
  37. void scambia_stringhe(char str1[], char str2[]) {
  38.     char temp_str[STR_LEN];
  39.  
  40.     copia_stringa(str1, temp_str);
  41.     copia_stringa(str2, str1);
  42.     copia_stringa(temp_str, str2);
  43. }
  44.  
  45.  
  46. // Ordina un array di stringhe in ordine alfabetico.
  47. // n e' il numero di stringhe.
  48. void ordina_alfabetico(char stringhe[][STR_LEN], int n) {
  49.     // Exchange Sort
  50.     for(int i = 0; i < n - 1; i++) {
  51.         for(int j = i + 1; j < n; j++) {
  52.             if(alfabetico_dopo(stringhe[i], stringhe[j])) {
  53.                 scambia_stringhe(stringhe[i], stringhe[j]);
  54.             }
  55.         }
  56.     }
  57. }
  58.  
  59.  
  60. int main() {
  61.     int n;
  62.     cout << "Quante stringhe?: ";
  63.     cin >> n;
  64.  
  65.     char stringhe[n][STR_LEN];
  66.     for(int i = 0; i < n; i++) {
  67.         cout << "Stringa " << i + 1 << ": ";
  68.         cin >> stringhe[i];
  69.     }
  70.  
  71.     ordina_alfabetico(stringhe, n);
  72.  
  73.     for(int i = 0; i < n; i++) {
  74.         cout << "Stringa " << i + 1 << ": ";
  75.         cout << stringhe[i] << endl;
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment