Sorting arrays with cyclic compares (infinite loop?)

Posted by Tiago on Stack Overflow See other posts from Stack Overflow or by Tiago
Published on 2010-02-24T17:00:03Z Indexed on 2010/03/30 15:03 UTC
Read the original article Hit count: 524

Filed under:
|
|
|

Hi,

I have some objects that have 3 sorting options: quality, quatity and a compare against the other object, sorted by that order.

- (NSComparisonResult) compare: (MyObject *) obj {
if (self.quality > obj.quality)
return NSOrderedAscending;
else if (self.quality < obj.quality)
return NSOrderedDescending;

if (self.quantity > obj.quantity)
return NSOrderedAscending;
else if (self.quantity < obj.quantity)
return NSOrderedDescending;

if ([self betterThan: obj])
return NSOrderedAscending;

if ([obj betterThan: self])
return NSOrderedDescending;

return NSOrderedSame;
}

My problem is that, the betterThan: method might cause a cyclic compare if the objects have the same quality and quantity, and I want to return any sort order in that case.

For example, A, B and C have the same quality/quantity, but

A betterThan: B => YES
B betterThan: C => YES
C betterThan: A => YES

Solutions? Thanks.

© Stack Overflow or respective owner

Related posts about sorting

Related posts about array