Sorting/sort function/comparator

https://online.codingblocks.com/app/player/49396/content/53507/6861?code=fQVF1R7pvANkIatBAiKaNAMPkNbDAI5A

line 10 : void bubble_sort (int a [ ] , int n , bool ( &cmp)( int
a , int b))

my doubt : why did we use &cmp? what’s the use of ’ & ’ here? please elaborate.

2nd doubt :

how exactly do comparators change the order( increasing or decreasing ) of sorting after being used in sort function?

Hi @prateek_5, here cmp is the reference to the function that is being passed as parameter and “&” is used for call by reference .
Note : If we had called "void bubble_sort (int a [ ] , int n , bool ( *cmp)( int
a , int b)) in that case it would be call by address and cmp would be pointer to the function passed in the parameter .

whenever we pass comparator function to a function ,say a sorting function , then all the comparisons are made through the comparator function so we can just modify the comparator function to get the desired order.

For a comparator function used for sorting , comparator function takes two argument say , comparator(data_type a, data_type b) then this function will return true if a should come first in the desired order and will return false if b should come first

In case of any doubt feel free to ask :slight_smile:
if you got your answer then mark your doubt as resolved
a like would be a bonus

1 Like

what happens inside sort function when ‘compare’ returns false? I want to know as to what exactly happens inside.

it will place second parameter before the first parameter in the resultant array

1 Like

what are the arguments of compare? i.e.

bool compare(int a , int b );

what is a and b in case when used inside sort( ) i.e. sort (array , array+n , compare) ?

in other words

are you saying that it compares between two arrangements(increasing & decreasing ) of the same array and returns as per true or false condition inside compare ( ) ?

lets take example of bubble sort inside your bubble sort you do
bubble_sort(arr,arr+n):
if (arr[i] <arr[i]) {
some operation
}bubble_sort(arr,arr+n):
if (arr[i] <arr[i]) {
some operation
}
lets make another bubble sort function which takes comparator function as argument
then something like this would happen

bubble_sort(arr,arr+n,compare ):
//instead of if (arr[i] <arr[i]) {
// we will have
if(compare(arr[i],arr[j]){
some operation
}

as u can see now the comparison now occurs depending on the way we implement compare function

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.