Please tell how this code is workinig, as I have not passed compare function to the bubble_sort function.
Comparator Understanding
you have written the sorting algorithm from scratch. the bubble_sort() function is designed by you and you decided to put only 2 arguments in the function so no need to pass compare function. it means if you are writing complete sorting algo, no need of passing compare function.
but in complex problems, where we need sorting as a part of task, we dont write sorting algo from scratch , we use sort() function which is inbuilt in cpp.
for eg. int arr[] = {1,4,3,2};
sort(arr,arr+4);
just two lines of code to sort the array. I have not defined sort() , just called it. now this sort function always sort in a fixed default way, like ascending order in this case.
when we want to sort in a custom way(other than default), using sort() function , we can tell the compiler to sort in our defined way by passing compare function.
bool compare(int a,int b)
{
cout<<“Compare”<<a<<“and”<<b<<endl;
//this function returns true when (conditon is true)
return a>b;
}
sort(arr,arr+n, compare); now this will sort in descending order.
thanks
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.