Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <string.h>
- using namespace std;
- const int STR_LEN = 25;
- // Restituisce true se str1 e' dopo str2 nell'ordine alfabetico.
- // Nota che non fa differenza tra lettere e altri caratteri, e si basa sulla tabella ASCII.
- bool alfabetico_dopo(char str1[], char str2[]) {
- int i;
- for (i = 0; str1[i] != '\0' && str2[i] != '\0'; i++) {
- if(str1[i] > str2[i])
- return true;
- else if (str1[i] < str2[i])
- return false;
- }
- // Restituisco vero se str1 e' piu' lunga di str2.
- // Esempio: francescoabcd e francesco, la prima e' dopo la seconda in ordine alfabetico.
- return str1[i] != '\0';
- // Oppure restituisco semplicemente false, dipende dall'idea.
- // return false;
- }
- // Copia la stringa src in dst.
- void copia_stringa(char src[], char dst[]) {
- int i;
- for(i = 0; src[i] != '\0'; i++)
- dst[i] = src[i];
- dst[i] = '\0';
- }
- // Scambia due stringhe.
- void scambia_stringhe(char str1[], char str2[]) {
- char temp_str[STR_LEN];
- copia_stringa(str1, temp_str);
- copia_stringa(str2, str1);
- copia_stringa(temp_str, str2);
- }
- // Ordina un array di stringhe in ordine alfabetico.
- // n e' il numero di stringhe.
- void ordina_alfabetico(char stringhe[][STR_LEN], int n) {
- // Exchange Sort
- for(int i = 0; i < n - 1; i++) {
- for(int j = i + 1; j < n; j++) {
- if(alfabetico_dopo(stringhe[i], stringhe[j])) {
- scambia_stringhe(stringhe[i], stringhe[j]);
- }
- }
- }
- }
- int main() {
- int n;
- cout << "Quante stringhe?: ";
- cin >> n;
- char stringhe[n][STR_LEN];
- for(int i = 0; i < n; i++) {
- cout << "Stringa " << i + 1 << ": ";
- cin >> stringhe[i];
- }
- ordina_alfabetico(stringhe, n);
- for(int i = 0; i < n; i++) {
- cout << "Stringa " << i + 1 << ": ";
- cout << stringhe[i] << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment