School-Coding-Cpp/sfusi/finsertionSort.cpp

102 lines
1.9 KiB
C++

/*
Nome: Mario
Cognome: Montanari
Classe: 3AIN
Data: 05/05/2025
Funzione di Insertion Sort che ordina direttamente su un file
*/
#include <iostream>
using namespace std;
typedef struct {
int value;
} basetype;
void finsertionSort(FILE * file);
void fprint(const char * filename);
int main(void) {
const char * filename = "data.bin";
FILE * file = fopen(filename, "r+b");
if (file != NULL) {
finsertionSort(file);
fprint(filename);
fclose(file);
} else {
perror("Error");
}
return 0;
}
void finsertionSort(FILE * file) {
fseek(file, 0, SEEK_END);
long n = ftell(file) / sizeof(basetype);
rewind(file);
for (int i = 1; i < n; i++) {
basetype key;
basetype temp;
fseek(file, i * sizeof(basetype), SEEK_SET);
if (fread(&key, sizeof(basetype), 1, file) < 1) {
cout << "Errore di lettura." << endl;
return;
}
int j = i - 1;
// Sposta gli elementi maggiori di key verso destra
while (j >= 0) {
fseek(file, j * sizeof(basetype), SEEK_SET);
if (fread(&temp, sizeof(basetype), 1, file) < 1) {
cout << "Errore di lettura." << endl;
return;
}
if (temp.value > key.value) {
fseek(file, (j + 1) * sizeof(basetype), SEEK_SET);
if (fwrite(&temp, sizeof(basetype), 1, file) < 1) {
cout << "Errore di scrittura." << endl;
return;
}
j--;
} else {
break;
}
}
// Inserire key nella posizione corretta
fseek(file, (j + 1) * sizeof(basetype), SEEK_SET);
if (fwrite(&key, 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");
}
}