PDA

View Full Version : [C] Insertion sort in struttura array strighe


gabmac2
04-05-2010, 14:20
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

gabmac2
06-05-2010, 19:36
nessuno?

nikel
06-05-2010, 21:07
non ho capito bene la tua richiesta... devi ordinare un array di struct in base all'id?

gabmac2
06-05-2010, 22:08
intanto grazie,si esattamente
ho un array di struct con i 3 campi char e dovrei ordinarlo per id

fero86
06-05-2010, 22:49
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;
}

gabmac2
06-05-2010, 22:59
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?

gugoXX
07-05-2010, 09:17
Ma lo scopo dell'esercitazione e' scrivere un insertion sort?

gabmac2
07-05-2010, 10:28
si