prem ktiw - 1 year ago 80
C Question

qsort and sort behaving differently in C++

I am very Amazed that how sorting via qsort and sort can produce different results ?
A help is needed in the behavior of following code segment

1. Done using qsort

// the follwing comparator has been used in qsort.
// if l<r : -1, l==r : 0 , l>r 1
int cmpre(const void *l, const void *r){
if((*(tpl *)l).fhf < (*(tpl *)r).fhf)return -1;
else if((*(tpl *)l).fhf == (*(tpl *)r).fhf){
if((*(tpl *)l).nhf == (*(tpl *)r).nhf) return 0;
else if((*(tpl *)l).nhf > (*(tpl *)r).nhf) return 1;
else return -1;
}
else return 1;
}
// and sort statement looks like :
qsort(tlst,len,sizeof(tpl),cmpre);

http://ideone.com/zN87tX

1. Done using sort

// the following comparator was used for sort
int cmpr(const tpl &l, const tpl &r){
if(l.fhf < r.fhf)return -1;
else if(l.fhf == r.fhf){
if(l.nhf == r.nhf) return 0;
else if(l.nhf > r.nhf) return 1;
else return -1;
}
else return 1;
}
// and sort statement looks like :
sort(tlst,tlst+len,cmpr);

http://ideone.com/37Dc2S

You can see the output on the link, after and before sorting operation and may wish to check out the compr and compre methods used to compare two tuples.
I do not understand why sort is not able to sort the array whereas qsort is able to do so.

Rewrite cmpr() as

bool cmpr(const tpl &l, const tpl &r){
if(l.fhf != r.fhf) return l.fhf < r.fhf;
return l.nhf < r.nhf;
}

Or, you may also reuse cmpre() to implement cmpr().

bool cmpr(const tpl &l, const tpl &r) {
return (cmpre(&l, &r) < 0);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download