Question -
Given an array of size N, sort it in such a way that the following conditions are satisfied:
I came up with the solution of using custom sort to sort the array - main() calls sort(arr, arr + n, comparator)
My solution -
bool comparator(const int &a, const int &b){
bool result;
// a is even and b is even
if(a%2 == 0 && b%2 ==0){
//as per condition (3)
if(a%5 == 0 && b%5 ==0)
result = a>b;
//as per cond (2)
else if(a%5!=0 && b%5 == 0)
result = false;
//as per cond (2)
else if(a%5 == 0 && b%5!=0)
result = true ;
//as per cond (4)
else
result = false ;
}
//a is even and b is odd - follow condition (1)
else if(a%2 == 0 && b%2 != 0)
result = true;
//a is odd and b is even - follow condition (1)
else if(a%2 !=0 && b%2==0)
result = false;
//both are odd - follow condition (5)
else
result = false;
return result;
}This code failed in few hidden test cases. Is there anything wrong with the custom comparator used in in-built sort()? As per my understanding, the comparator(a,b) should return true if a must come before b else return false. Seems like this may not be right. Can someone clarify if any changes are to be made in the comparator or is there any better solution to this problem.