Since you already asked how to add the second field previously in this question, I believe it is best to explain how the comparison of two fields or more works. This way you can include as many as you want.
I’m assuming you know how the Bubble Sort, which is the sorting algorithm implemented in the function you posted along with the question.
When you want to compare two objects based on just one property, just check if the first property of the object a
is greater than or equal to the first property of the object b
and make the exchange if positive. Example:
if (a.primeira() >= b.primeira()) {
// troca ordem
}
When you have a second property and need to sort, you must first compare whether the first property of the object a
is greater that the same property of the object b
and, if true, you must exchange. If it is not true, you must then check whether the first property of the object a
is equal the same property of the object b
And if the second property of the object a
is greater or equal to the same property of the object b
. Example:
if ((a.primeira() > b.primeira()) ||
(a.primeira() == b.primeira() && a.segunda() >= b.segunda())) {
// troca ordem
}
To add the third property just do the same thing we did to add the second: when comparing the second property do the exchange if the second property is greater or if the second is equal and the third for greater or equal. Example:
if ((a.primeira() > b.primeira()) ||
(a.primeira() == b.primeira() && a.segunda() > b.segunda())) {
(a.primeira() == b.primeira() && a.segunda() == b.segunda() && a.terceira() >= b.terceira())) {
// troca ordem
}
So far the code is still readable, but in case you intend to add several other properties I recommend you think of a more readable comparison algorithm.
Anyway, its function ordenaPorCursoENomeESituacao()
would be as follows:
vector<Aluno> ordenaPorCursoENomeESituacao(vector<Aluno> lista){
for(int i = 0 ; i < lista.size() ; i++){
for(int j = i ; j < lista.size() ; j++){
if ((lista[i].getCurso() > lista[j].getCurso()) ||
(lista[i].getCurso() == lista[j].getCurso() && lista[i].getNome() > lista[j].getNome()) ||
(lista[i].getCurso() == lista[j].getCurso() && lista[i].getNome() == lista[j].getNome() && lista[i].getSituacao() >= lista[j].getSituacao())) {
Aluno temp = lista[j];
lista[j] = lista[i];
lista[i] = temp;
}
}
}
return lista;
}