Due to the installation of a new fire alarm in ITMO server room, the system may be occasionally unavailable on the 27-th of May between 06:00 and 15:00 (UTC). ×

jk_birla's blog

By jk_birla, history, 5 weeks ago, In English,

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.

 
 
 
 
  • Vote: I like it  
  • -3
  • Vote: I do not like it  

»
5 weeks ago, # |
  Vote: I like it +6 Vote: I do not like it
  • »
    »
    5 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I have tried to google but still not cleared with it. Can you pls help me?

    • »
      »
      »
      5 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      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.

      • »
        »
        »
        »
        5 weeks ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        So If I need to sort the pair according to the same method then I just need to do like.
        bool myfunction (pair<int,int> i,pair<int,int> j) { return (i.first*j.second<j.first*i.second); }
        //what exactly is returning i<j doing?

        • »
          »
          »
          »
          »
          5 weeks ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          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;
          
          • »
            »
            »
            »
            »
            »
            5 weeks ago, # ^ |
              Vote: I like it 0 Vote: I do not like it

            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?

            • »
              »
              »
              »
              »
              »
              »
              5 weeks ago, # ^ |
                Vote: I like it 0 Vote: I do not like it

              Your code above is OK.

              Since comparison takes O(1), the whole sort method is O(NlogN).

        • »
          »
          »
          »
          »
          5 weeks ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          yes, and after that do sort(.., .., myfunction)