Can you please explain what logic they use inside the sort function body such that if we pass a comparator function with the body having a < b, then it sorts the array in ascending order and if we pass comparator function having a > b in the body then it sorts in the Descending order.
Working of the sort() function of the algorithm header file
sorting is simply rearranging the elements. it means deciding which elements comes first between each pair of element(like you do swap/non swap in bubble sort).
so the logic is,
consider the compare function as
bool compare(int a, int b){
// returning true means: a will be placed before b in new arrangement
//returning false means : b will come before a in new arrangement
}
so
- return a<b : will return true when a is less than b, means a comes first when a <b… this is ascending order.
- return a>b: will return true when a is greater than b, means a comes first when a>b… this is descending order.
thanks
Thank you for explaining and well explained. Thanks.
please rate if satisfies. 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.
Sorry but the link directs to the page not found