如何对这个 NSMutableArray 进行排序?
我创建了一个名为 Person 的类。看起来像这样
Person
-------
Name
Points
然后我创建了一个名为 team 的 NSMutableArray。它包含几个这样的 person 对象。我创建了几个团队。
然后我创建了另一个名为 allTeams 的 NSMutableArray。它拥有所有的团队阵列。
我想按每个团队的总得分对 allTeams 数组进行排序,该总得分是通过对团队中每个人的得分求和得出的。
我该怎么做?
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 create 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有必要搞乱无关的ivars,除非你有数百万玩家和数十万支球队,否则简单的实施将比你可能需要的更快。
免责声明:我在没有访问我的 Mac 的情况下编写了上述代码,因此它可能无法按编写的方式编译,但它已经接近了。祝你好运!
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.
Disclaimer: I wrote the above code without access to my Mac, so it may not compile as written, but it's close. Good luck!
为什么不在 team 对象中维护一个 int 变量来表示团队中每个人的累积分数?当您想要进行比较时,只需根据该字段进行排序即可。任何排序算法都可以工作,但有明显的内存要求(就地与额外分配的内存)和最坏情况运行时间(O(n ^ 2),O(nlog(n))的警告。
所有分数的计算第一次请求排序信息时,团队的时间复杂度为 O(n^2)。 此后,每次有人得分时,只需调用更新该人得分的选择器,然后更新团队得分。
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.