64 lines
1.5 KiB
C++
64 lines
1.5 KiB
C++
#include <iostream>
|
|
#include <cstdlib>
|
|
#include <ctime>
|
|
|
|
using namespace std;
|
|
|
|
typedef struct {
|
|
int anno;
|
|
float num;
|
|
char parola[10+1];
|
|
} Struttura;
|
|
|
|
int cmp_str(const void * a, const void * b) {
|
|
const Struttura * pa = (const Struttura*)a;
|
|
const Struttura * pb = (const Struttura*)b;
|
|
|
|
// return (strcmp(pa -> parola, pb -> parola)); // Ordinati per stringa crescente
|
|
return (pb -> anno - pa -> anno); // Ordinati per anno decrescente
|
|
// return (pa -> num > pb -> num) - (pa -> num < pb -> num); // Ordinati per float crescente
|
|
}
|
|
|
|
int main(void) {
|
|
srand(time(NULL));
|
|
|
|
cout << "sizeof(Struttura): " << sizeof(Struttura) << endl << endl;
|
|
|
|
FILE * file = fopen("esercizio_qsort.bin", "wb");
|
|
|
|
if (file != NULL) {
|
|
Struttura s[5];
|
|
|
|
cout << "Dati originali:" << endl;
|
|
for (int i = 0; i < 5; i++) {
|
|
s[i].anno = rand() % (2025 - 1900 + 1) + 1900;
|
|
s[i].num = rand() % (50 + 0 + 1) + 0;
|
|
float dec = s[i].num;
|
|
dec = dec / 10;
|
|
s[i].num += dec;
|
|
|
|
for (int j = 0; j < 10; j++) {
|
|
s[i].parola[j] = rand() % (25 + 0 + 1) + 'A';
|
|
}
|
|
s[i].parola[10] = '\0';
|
|
|
|
cout << s[i].anno << " " << s[i].num << " " << s[i].parola << endl;
|
|
}
|
|
|
|
cout << endl << "Dati ordinati:" << endl;
|
|
|
|
qsort(&s, 5, sizeof(Struttura), cmp_str);
|
|
|
|
for (int i = 0; i < 5; i++) {
|
|
cout << s[i].anno << " " << s[i].num << " " << s[i].parola << endl;
|
|
}
|
|
|
|
fwrite(&s, sizeof(Struttura), 5, file);
|
|
|
|
fclose(file);
|
|
} else {
|
|
perror("Error");
|
|
}
|
|
|
|
return 0;
|
|
} |