prem ktiw prem ktiw - 9 days ago 5
C++ Question

qsort and std::sort behaving differently

I am very amazed that sorting via

qsort
and
std::sort
can produce different results. I need help explaining the behavior of the following snippets:


  1. using
    qsort
    :

    // the following 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);


    Complete Code link =>
    http://ideone.com/zN87tX

  2. 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);


    Complete code link at =>
    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.

Answer

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);
}