# Problem in Sorting structure

• hai I am implemented one logic to sort array of structure

Is shown below

@struct library
{
char Nuclide_name[20];
float Nuclide_energy;
};@

@
bool caseInsensitiveLessThan(const library &n1, const library &n2)
{
return n1.Nuclide_energy<n2.Nuclide_energy
}
@
@for(int i=0;i<4;i++)
qDebug()<< QString::number(Nuclide[i].Nuclide_energy)<<Nuclide[i].Nuclide_name;
QList<library> list;
for(int i=0;i<4;i++)
{
list.append(Nuclide[i]);
qDebug()<< QString::number(Nuclide[i].Nuclide_energy)<<Nuclide[i].Nuclide_name;
}

``````qSort(list.begin(),list.end(),caseInsensitiveLessThan);
qDebug()<<"sorting completed"<<QString::number(list.count());
for(int i=0;i<4;i++)
qDebug()<< QString::number(Nuclide[i].Nuclide_energy)<<Nuclide[i].Nuclide_name;@
``````

is there any mistake in my code?
I wrote this code with refence of this"qsort":http://qt-project.org/doc/qt-4.8/qtalgorithms.html#qSort-2

• Hi,

you're printing the wrong contents:

the last for loop shall be substituted with

@
for(int i=0;i<4;i++)
qDebug()<< list[i].Nuclide_energy<<list[i].Nuclide_name;
@

• In list the data is appended but it is not sorted after qSort

Is qSort() is work for structers or not

• Hi,

this code works well for me

@
void Widget::on_pushButton_clicked()
{
library Nuclide[4];
for (int i = 0; i < 4; ++i) {
Nuclide[i].Nuclide_energy = 4 - i;
sprintf(Nuclide[i].Nuclide_name, "Nuclide_%d", i);
}

``````for(int i=0;i<4;i++)
qDebug()<< QString::number(Nuclide[i].Nuclide_energy)<<Nuclide[i].Nuclide_name;

QList<library> list;
for(int i=0;i<4;i++)
{
list.append(Nuclide[i]);
qDebug()<< QString::number(Nuclide[i].Nuclide_energy)<<Nuclide[i].Nuclide_name;
}

qSort(list.begin(),list.end(),caseInsensitiveLessThan);
qDebug()<<"sorting completed"<<QString::number(list.count());

for(int i=0;i<4;i++)
qDebug()<< list[i].Nuclide_energy<<list[i].Nuclide_name;
``````

}
@

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.