How to sort NSMutableArray? Code review needed
- by JAM
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;
}
}
}
}
}
}