bool comp(int a,int b){
if ((a > 0 && b > 0) || (a < 0 && b < 0))
return false;
if ((a > 0) && (b < 0))
But I am unable to understand how it is working, Could someone explain ?
I try to explain how it's supposed to work, but actually, it does not work :)
bool comp(int a, int b) {
if((a > 0 && b > 0) || (a < 0 && b < 0))
return false;
if((a > 0) && (b < 0))
return false;
return true;
}
This code tries to compare signs: checking whether sign of a is "less" than sign of b. Assuming that negative is "less" than positive. So, sign of -1 is less than sign of 1, and sign of -3 is not less than sign of -1.
The problem here is that comparator should always conform with https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.
In short, strict weak ordering is: for any a and b, only one condition is true: a < b, or b < a, or b == a. There should be no case when more of one condition is true.
When strict weak ordering is violated in production code, very bad things will happen: overtimes, failed deadlines, and even worse.
Your sort() will fail on this array: { 1, 0, 2, 0, -3, 0,-1 } because strict weak ordering is violated: both comp(-1, 0) is true and comp(0, -1) is true.