/* Nome: Mario Cognome: Montanari Classe: 3AIN Data: 05/05/2025 Funzione di Selection Sort che ordina direttamente su un file */ #include using namespace std; typedef struct { int value; } basetype; void fselectionSort(FILE * file); void fprint(const char * filename); int main(void) { const char * filename = "data.bin"; FILE * file = fopen(filename, "r+b"); if (file != NULL) { fselectionSort(file); fprint(filename); fclose(file); } else { perror("Error"); } return 0; } void fselectionSort(FILE * file) { fseek(file, 0, SEEK_END); long n = ftell(file) / sizeof(basetype); rewind(file); // Ciclo di ordinamento per Selection Sort for (int i = 0; i < n - 1; i++) { basetype cur; basetype baseMin; basetype min; fseek(file, i * sizeof(basetype), SEEK_SET); if (fread(&min, sizeof(basetype), 1, file) < 1) { cout << "Errore di lettura."; return; } baseMin = min; int minPos = i; for (int j = i + 1; j < n; j++) { fseek(file, j * sizeof(basetype), SEEK_SET); if (fread(&cur, sizeof(basetype), 1, file) < 1) { cout << "Errore di lettura." << endl; return; } if (min.value > cur.value) { min = cur; minPos = j; } } // Se il minimo non è già nella posizione i, scambia if (minPos != i) { // Scrivi il valore minimo nella posizione i fseek(file, i * sizeof(basetype), SEEK_SET); if (fwrite(&min, sizeof(basetype), 1, file) < 1) { cout << "Errore di scrittura." << endl; return; } // Scrivi il valore che era in posizione i nella posizione minPos fseek(file, minPos * sizeof(basetype), SEEK_SET); if (fwrite(&baseMin, sizeof(basetype), 1, file) < 1) { cout << "Errore di scrittura." << endl; return; } } } } void fprint(const char * filename) { FILE * file = fopen(filename, "rb"); if (file != NULL) { basetype temp; while (fread(&temp, sizeof(basetype), 1, file) == 1) { cout << temp.value << " "; } cout << endl; fclose(file); } else { perror("Error"); } }