How to sort NSMutableArray? Code review needed

Posted by JAM on Stack Overflow See other posts from Stack Overflow or by JAM
Published on 2011-11-19T01:40:09Z Indexed on 2011/11/19 1:50 UTC
Read the original article Hit count: 145

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;
                    } 
                }
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about sorting