Doubt in Compare Function

In bubble sort we use condition a [ j ] > a [ j + 1 ] for sorting in increasing order.
I am confused when we use compare function and return a > b how does that make return array in decreasing order

I mean when we pass compare function in sort(STL) function

please see this code for how to sort function in decreasing order using sort function

Yes but my doubt is that if I use the same comparator function in bubble sort to compare in second loop of the bubble sort. I will get the array is increasing order. And the code you shared outputs array in decreasing order. So why does this happen in STL sort function?

1 Like

In bubble sort what are you planning to use for the condition,
let say a[j] > a[j+1] is true
then, (what you want? is the question)
#Case1 , if above condition is true then, keep the numbers as it is otherwse swap. This will result in decreasing order sort.

#Case2 , if above condition is true then, swap the numbers otherwse keep as it is. This will result in increasing order sort.

So, inbuilt sort uses Case1 type comparison always.

1 Like

Yes that’s true. But what about STL sort function when compare function return a > b the array returned is in decreasing order. Should i just remember when,
CASE 1:
bool compare(int a, int b) {
return a > b;
}
sort(a, a + n, compare)
returns array in decreasing order.
CASE 2:
bool compare(int a, int b) {
return a < b;
}
sort(a, a + n, compare)
returns array in increasing order.

Or do you have anything to add about details of STL sort function working

when you simply write
sort(a,a+n)
this will return increasing order by default.
and when you give some comparator, it will go according to that

the idea is intuitive:
for example given a[] = 1 5 6 2 3
and I say you to sort with comparator a>b
then what u think? you will sort in such way that a>b should hold for number a appearing before b

that is 6 > 2 and 6 is before 2, this is in good position but,
2 !> 3 so we have to rearrange them

1 Like

I just needed this clarification and didnt want to just remember it. This idea clears my doubt. Thanks!

1 Like

If you are happy with this clarification!
Please mark this as resolved doubt and rate me!

How do I rate you Rahul?

you might have rated while marking this doubt as resolved !
Nothing serious! if you didn’t find that, then its OK,

Regards from rkrishna :blush::blush:

1 Like

Ohh ha! 5 start dont worry :grin: