Good evening.
This code works. It sorts an array of cards by both Suit and Card Value. It is also very much brute force. Can you recommend a better way? Does Objective-C help dealing with a situation where object being sorted itself has multiple fields, on which sorting depends?
-(void) sort: (NSMutableArray *) deck {
NSUInteger count = [deck count];
Card *thisCard;
Card *nextCard;
int this;
int next;
BOOL stillSwapping = true;
while (stillSwapping) {
stillSwapping = false;
for (NSUInteger i = 0; i < count; ++i) {
this = i;
next = i+1;
if (next < count) {
thisCard = [deck objectAtIndex:this];
nextCard = [deck objectAtIndex:next];
if ([thisCard suit] > [nextCard suit]) {
[deck exchangeObjectAtIndex:this withObjectAtIndex:next];
stillSwapping = true;
}
if ([thisCard suit] == [nextCard suit]) {
if ([thisCard value] > [nextCard value]) {
[deck exchangeObjectAtIndex:this withObjectAtIndex:next];
stillSwapping = true;
}
}
}
}
}
}
You have several options.
Perhaps the simplest is to define the method
-compare:onCard, which returns anNSComparisonResult. This is preferable if sorting by suit and value is the “standard” way to sort aCard. If you’ve done this, then your entire sorting method can be turned intoIf you don’t want to do this, you can use an array of
NSSortDescriptors, one for suit and one for value.If this doesn’t work for whatever reason, you could try
-sortUsingComparator: