I am using comparator for sorting strings according to their lengths.
bool compare(string a,string b){
return a.length > b.length
}
shouldn’t this sort in ascending order ? Why in my case it doing that in descending order
I am using comparator for sorting strings according to their lengths.
bool compare(string a,string b){
return a.length > b.length
}
shouldn’t this sort in ascending order ? Why in my case it doing that in descending order
Since you are using > , it will sort in descending order or say after sorting the largest length string will be at the beginning. If you use < then smallest length string will be at the beginning.
So remember this > – then descending
< – then ascending
how does it relate to swap function… If a = 9, b = 6.
In your doubt, you considered a and b as string.
However if a=9 and b=6
If you want sort in descending order… then you would return a>b… means when a will be less than b…only then swapping will take place. So result will be 9,6
If you want sort in ascending order… then you would return a<b… means when a will be greater than b…only then swapping will take place. So result will be 6,9
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.