Identical qsort vs std :: sort result

I apologize for the brevity of the message.

I have an array of records. I want to sort it descending wrt one of its keys. Entries "are not unique.

compare qsort function:

int cmp(const record* rec1, const record* rec2) 
{
    return rec2->key - rec1->key;
}

compare the function std :: sort:

bool operator()(const record& rec1, const record& rec2) 
{
    return rec1.key > rec2.key;
}

Will both versions have the same result? I'm not sure if sort / qsort behave the same when keys are equal.

+4
source share
2 answers

There are no such guarantees.

std::qsort:

If comptwo elements are indicated as equivalent, their order is not specified.

std::sort:

The order of equal elements is not guaranteed.

You need a stable sorting algorithm if you need to keep the order of equal elements. std::stable_sortis stable.

, .

+3

. stable. , , , .

[alg.sort] , , / . , ++ 11 std:: sort O (n log n), , std:: qsort , - ( , Bogosort qsort)


, GCC , , , , "".

  • GCC? ( std:: sort, it "Introsort" )

qsort libc, GCC.

+2

Source: https://habr.com/ru/post/1684157/


All Articles