在NSMutableDictionary

时间:2016-07-10 02:02:15

标签: objective-c sorting nsmutabledictionary

我有一个NSMutableDictionary,我想打印出来作为键:排序顺序的值(其中键是这样的,首先打印具有较低值的键)。

要做到这一点,我使用的是NSSictionary的keysSortedByValueUsingComparator:方法,如下所示。

有没有人知道底层实现是否使用快速排序方法并实现O(N * logN),还是将每个对象与每个其他对象进行比较,从而导致O(N ^ 2)复杂度?

示例:

NSMutableDictionary *hashTable = [[NSMutableDictionary alloc] init];
....
code that adds a bunch of Objects to the hashtable dictionary with key = NSString and value = NSNumber object
....
NSArray * sortedKeys = [hashTable keysSortedByValueUsingComparator:^(id  _Nonnull obj1, id  _Nonnull obj2) {
           if ([obj1 integerValue] > [obj2 integerValue])
           {
               return (NSComparisonResult)NSOrderedDescending;
           }

           if ([obj1 integerValue] < [obj2 integerValue])
           {
               return (NSComparisonResult)NSOrderedAscending;
           }

           return (NSComparisonResult)NSOrderedSame;
       }];

for (NSString *nextKey in sortedKeys)
{
   NSLog(@"%@: %@",nextKey,hashTable[nextKey]);
}

1 个答案:

答案 0 :(得分:1)

似乎使用合并排序 - 当然是O( n log n )。已知其他排序方法使用快速排序。

如何猜测:在比较器块内放置一个断点,并在命中时读取堆栈跟踪。在您的代码中,您将看到CFSimpleMergeSort正在调用比较器。除非Apple程序员有一个有趣的命名方案,否则这是一个很好的猜测,即合并排序!

也许如何确定:主NS个收藏集是免费的,与他们的CF对应者联系在一起,CF来源可以从Apple的开源获得现场。搜索CFArray.cCFDictionary.c等,您就会找到来源。这将不包括所有NS方法,因此&#34;可能会找出&#34;,但它会显示这些类型的工作方式。

HTH