What arguments are passed to the compare function by the sort STL function? Is it the 1st and the 2nd element of the array?
What I am really asking is, what is the order in which the comparator function is passed the arguments by the sort function in terms of the range of the array indices? Is it always like: comparator(a, b) , where ‘a’ will be an element at a lower index than the index of ‘b’? Because there should be some standardization as the order will make a difference.
Or if there is something else to this?
I believe that what you’re asking is actually “is std::sort stable?”.
A stable sort is a sort that won’t swap values if they evaluate the same. They’ll be in the same order than before the sort.
std::sort is not guaranteed to be stable, but std::stable_sort is.
You must use a strict comparison in the compare function, though.
For example, if your criteria for higher ranking is a >= b, it won’t preserve the order even if you use std::stable_sort.
Is it always (by default) like: comparator(a, b) , where ‘a’ will be an element at a lower index than the index of ‘b’ ?
Could you answer this for now?
I’ll read about the “stable sort” as well.
And thanks for the explanation.
Well, it can be interesting to know if the sort is stable or not. It’s part of the contract.
But the implementation doesn’t really matter.
But if you really want to know, std::sort is usually implemented with intro sort, which doesn’t always uses compare(a, b) with a of lower index than b. Hence the potential instability.
And std::stable_sort is usually implemented with merge sort, which always uses compare(a, b) with a of lower index than b. Hence the stability cause if a evaluates the same as b, b won’t be swapped with a so first equally evaluated stays first.
Note for Nicola: he opened a new thread cause his question was misundertood, which I believe is legitimate. It’s a technical question that is not directly answered in cpp doc, especially if you don’t know what sort stability is.
Hey! But if you really want to know, std::sort is usually implemented with intro sort, which doesn’t always uses compare(a, b) with a of lower index than b. Hence the potential instability.
This is interesting! And this was the kinda answer I was looking for.
So thanks a lot for the explanation and for understanding on me opening a new thread! Much appreciated.