开发者

How to sort this NSMutableArray?

I made a class called Person. It looks like this

Person
-------
Name
Points

Then I created an NSMutableArray called team. It contains several of these person objects. I creat开发者_Python百科e several teams.

Then I created another NSMutableArray called allTeams. It holds all the team arrays.

I want to sort the allTeams array by the total number of points for each team, found by summing the points for each person in the team.

How can I do this?


No need to muck around with extraneous ivars, unless you have millions of players and hundreds of thousands of teams, the naive implementation will be faster than you could possibly need.

@interface Team : NSObject {
    NSMutableArray *people;
}

@property (readonly) NSInteger score;

@end

@implimentation Team

- (NSInteger)score {

    NSInteger score = 0;

    for(Person *person in people) {
        score = score + person.points;
    }

    return score;
}

@end

// To sort an array of teams, do the following
// assumes that `teams` is a mutable array containing all teams

NSSortDescriptor *scoreSort = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO];
[teams sortUsingDescriptors:[NSArray arrayWithObject:scoreSort]];
[scoreSort release];

Disclaimer: I wrote the above code without access to my Mac, so it may not compile as written, but it's close. Good luck!


Why not maintain an int variable in the team object that is the cumulative score of each person on the team? When you wanted to do the comparison, simply sort based on that field. Any sort algorithm will work, with the obvious caveats of memory requirements (in place vs. extra allocated memory) and worst case running time (O(n^2), O(nlog(n)).

The calculation of the scores for all teams would be O(n^2) the first time the sort information is requested. After that, each time a person scores a point, simply call a selector that updates that persons score and then update the team score.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜