View Full Version : [C] Insertion sort in struttura array strighe
Avendo una struct
contenente ID,nome e cognome (3 stringhe)
dovrei ordinarla in modo da avere a ogni inserimento la struttura ordinata,per ID
void ordina( struct array *b,struct array *ins, int n ) {
struct array temp[N];
int i;int j=0;
for(i=0;i<n;i++){
while(b[i].id>ins[i].id){
strcpy(temp[i].id,b[i].id);
strcpy(temp[i].nome,b[i].nome);
strcpy(temp[i].cognome,b[i].cognome);
i++;}}
avrei iniziato così,è una traccia corretta,ma sono bloccato,mi dite come proseguire?
Grazie in anticipo
non ho capito bene la tua richiesta... devi ordinare un array di struct in base all'id?
intanto grazie,si esattamente
ho un array di struct con i 3 campi char e dovrei ordinarlo per id
io continuo a propagandare l'uso del C++:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
const size_t cstr = 6;
string astr[cstr] = {
"ciao", "come", "stai", "bene", "grazie", "prego",
};
for (int i = 1; i < cstr; i++) {
string str = astr[i];
int j = i - 1;
while (astr[j] > str) {
astr[j + 1] = astr[j];
if (--j < 0) {
break;
}
}
astr[j + 1] = str;
};
for_each(astr, astr + cstr, [] (string str) {
cout << str << endl;
});
return 0;
}
be grazie mille,uso c "obbligatoriamente" per un esercitazione
Però andiamo per passi,dovrei a ogni inserimento ordinare la struttura,che deve rimanere sempre ovviamente ordinata
il codice che hai postato mi ha confermato le idee che avevo per quanto riguarda l' algoritmo,stato provando un insertion sort,ma sono ancora bloccato
void insertion_sort(struct studarray *x, int n) {
int i, j;struct studarray app;
for (i=1; i<n; i++) {
app = x[i+1];
j = i-1;
while (j>=0 && (strcmp(x[j].id,---->app[i+1]<----.id)>0)){
x[j+1] = x[j];
j--;
}
x[j+1] = app;
}
return;
}
facendo cos' app non può essere inizializzato a una pos +1,essendo una struttura ,come posso fare?
Ma lo scopo dell'esercitazione e' scrivere un insertion sort?
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.