jk_birla's blog

By jk_birla, history, 6 months ago, ,

Can anybody tell me how to sort using Comparator in C++ in any specific order what are the condition required for such sorting and also what is the time complexity for sorting using comparator.
Example sort the pairs (1,2),(3,4),(6,10),(7,2) on the basis of if( ( a1 / b1 ) < ( a2 / b2 ) ) then (a1,b1) pair should come first in the order.

• -3

 » 6 months ago, # |   +6
•  » » 6 months ago, # ^ |   0 I have tried to google but still not cleared with it. Can you pls help me?
•  » » » 6 months ago, # ^ |   0 first link in the google searching list:http://www.cplusplus.com/reference/algorithm/sort/I am not sure if it can be explained even more clear.
•  » » » » 6 months ago, # ^ |   0 So If I need to sort the pair according to the same method then I just need to do like. bool myfunction (pair i,pair j) { return (i.first*j.second
•  » » » » » 6 months ago, # ^ |   0 In your code, myfunction returns if the pair i should come before the pair j.Returning i < j (which is the default), will compare it by first then second: if(i.first == j.first) return i.second < j.second; return i.first < j.first; 
•  » » » » » » 6 months ago, # ^ |   0 So if I want to sort according to a_i/b_i then my code will work. One last thing what can we say about the time complexity of this sorting and why?
•  » » » » » » » 6 months ago, # ^ |   0 Your code above is OK.Since comparison takes O(1), the whole sort method is O(NlogN).
•  » » » » » 6 months ago, # ^ |   0 yes, and after that do sort(.., .., myfunction)