Re: problem with C++ sort algorithm
jo_atman@yahoo.com wrote:
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
int retVal = s2->getPDClose() - s1->getPDClose();
if ( retVal != 0 ) return retVal < 0;
return s1->getAllocation() - s2->getAllocation();
}
I probably would have written this:
bool compareByCloseAndAlloc( State* s1, State*s2)
{
//compare by Alloc if Close are equal
if (s1->getPDClose() == s2->getPDClose())
{
return (s1->getAllocation() < s2->getAllocation());
}
//otherwise compare by Close
return (s1->getPDClose() < s2->getPDClose());
}
Notice that it would have made clear the bug in the code (I assume)
where you switch s1 and s2 in the 3rd to the 5th line.
Well, this guy asked me why i'm returning a boolean (retVal < 0) on
line 2, but an integer on line 3. I said, well, C++ really uses ints as
bool, and that i could change the code to
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
int retVal = s2->getPDClose() - s1->getPDClose();
if ( retVal != 0 ) return retVal < 0;
retVal = s1->getAllocation() - s2->getAllocation();
return retVal < 0;
}
but it wouldn't make a shred of a difference. And it did. It fixed the
problem.
Possibly because your boolean algebra is faulty.
If x is greater than y, then: x - y is true, x - y < 0 is false
If x is equal to y, then: x - y is false, x - y < 0 is false
If x is less than y, then: x - y is true, x - y < 0 is true
Your code may run without bombing out, but I have to wonder whether it
actually does what it is supposed to.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]