I would like your guidance to sort alphabetically by name, I am using a bubble method but it does not work for me and the sorting methods really confuse me. Thanks.
I tried to use the shel method but it was also difficult for me
struct persona {
int codigo;
string nombre;
string nombre_Materia;
double nota1,nota2,nota3,nota_final;
};
persona e[7];
int main(){
int size;
cout<<"Ingrese el tamaño de Lista de estudiantes : ";
cin>>size;
for(int i=0;i<=size;i++)
{
system("cls");
cout<<"Ingrese los datos de la persona: " <<i+1<<"\n";
cout <<"Ingrese el codigo: "<<endl;
cin>>e[i].codigo;
cout <<"Ingrese el nombre: "<<endl;
cin>>e[i].nombre;
cout <<"Ingrese el nombre de la materia: "<<endl;
cin>>e[i].nombre_Materia;
cout <<"Ingrese la nota 1: "<<endl;
cin>>e[i].nota1;
cout <<"Ingrese la nota 2: "<<endl;
cin>>e[i].nota2;
cout <<"Ingrese la nota 3: "<<endl;
cin>>e[i].nota3;
e[i].nota_final = e[i].nota1 * 0.30 + e[i].nota2 * 0.30 + e[i].nota3 * 0.40;
}
int i, j;
persona tempo;
for(i=0; i<size-1; i++)
for(j=i+1; j<size; j++)
if( (e[i].nombre > e[j].nombre) || (e[i].nombre == e[j].nombre && e[i].nombre> e[j].nombre) )
{
tempo = e[i];
e[i] = e[j];
e[j] = tempo;
}
//Declarmaos un for para que lea el vector persona2
for(int j=0;j<=size;j++)
{
cout<<"Mostrando persona:"<<j+1<<"\n";
cout<<"Persona: "<<e[j].codigo<<"\n";
cout<<"Persona: "<<e[j].nombre<<"\n";
cout<<"Persona: "<<e[j].nombre_Materia<<"\n";
cout<<"Persona: "<<e[j].nota_final<<"\n";
}
};
Reduce the number of iterations of this last loop by 1:
On the other hand, notice that the ordering condition doesn't make much sense:
The ordering, I understand, is ascending, so this conditional can be simplified quite a bit, since you only have to check if the first name is bigger than the second:
Otherwise the code seems to work fine.
I had a long time without using bubble so I took the code from this page: http://c.conclase.net/orden/?cap=burbuja Applying that code with your example, your order would be like this:
I have tried it and it has worked for me, as extra data, in your for where you ask the data you had <= and there it should only be the < because if it is not executed an extra time. I put the code of how I had the final code and apparently it worked, I hope it helps you
Your approach to the problem is more complicated than necessary. Simply define the ordering relationship between instances of
persona
and delegate the ordering to a standard library algorithm .Let's start by defining a less than operator (
<
) for objectspersona
:With this operator defined, you will be able to sort:
Your code might look something like this:
You can see it working in TIO.