Noor210111's blog

By Noor210111, history, 7 months ago, In English

In the following sort function of C++ how the 3rd argument is working?

sort(a.begin(), a.end(), [](int x, int y) { return x % 2 < y % 2; });

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

»
7 months ago, # |
  Vote: I like it 0 Vote: I do not like it

During comparison-based sorting, you need a way to figure out an "order", i.e. which element goes before another element. The third argument does that for the case N=2, in comparing the relative order of 2 elements. This function just helps you figure out the order of x and y for any arbitrary x and y. Note that your comparator must follow some basic properties, else you won't get the expected results. Link to very helpful blog

»
7 months ago, # |
  Vote: I like it 0 Vote: I do not like it
1. (_) % X => [0, X-1]

2. (_) % 2 => [0, 1]

3. EVEN % 2 < ODD % 2

You can observe the third argument is sorting the array based on the above results. Since (even) % 2 < (odd) % 2, all the even elements will get pushed to left extremity of the array and vice versa for odd elements.

Now if you want to preserve the non-decreasing nature on the two counterparts (odd & even) you can modify the function as follows.

Spoiler