有幾種方法可以做到這一點,其中一種方法是使用輔助NSCountedSet
實例和使用NSCountedSet
進行比較的函數:
NSInteger countedSort(id obj1, id obj2, void *context) {
NSCountedSet *countedSet = context;
NSUInteger obj1Count = [countedSet countForObject:obj1];
NSUInteger obj2Count = [countedSet countForObject:obj2];
if (obj1Count > obj2Count) return NSOrderedAscending;
else if (obj1Count < obj2Count) return NSOrderedDescending;
return NSOrderedSame;
}
和
NSMutableArray *array = …;
NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
autorelease];
[array sortUsingFunction:countedSort context:countedSet];
編輯: extremeboredom^h如巧妙地注意到,如果兩個不同的對象具有相同的重複計數,則它們的相應元素在結果數組中不一定是連續的。只有在相同對象不需要連續的情況下才需要使用此解決方案。
此外編輯:以便在需要表示同一對象的元件是連續的,則可以創建具有不同元件只,可以通過重複計數排序的更小的陣列。然後,創建另一個數組,其元素按重複次數排序。根據您的需要,您可能實際上不需要生成的陣列 - 可能只有distinctArray
&計數的設置就足夠了。
NSMutableArray *array = …;
NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
autorelease];
// Array with distinct elements only, sorted by their repeat count
NSArray *distinctArray = [[countedSet allObjects]
sortedArrayUsingFunction:countedSort context:countedSet];
// Array with all the elements, where elements representing the same
// object are contiguous
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in distinctArray) {
for (NSUInteger i = 0; i < [countedSet countForObject:object]; i++) {
[sortedArray addObject:object];
}
}
當你有對象的兩個「組」具有相同的大小,你期待什麼行爲?說object2,object3,object4是同一個對象,而object1,object7,object8是同一個對象。由於這兩個對象出現次數最多,它們的相應數組元素是否需要在結果數組中連續? – 2011-06-08 10:53:27