代码之家  ›  专栏  ›  技术社区  ›  Jonah

如何从另一个已排序的数组中获取索引数组?

  •  2
  • Jonah  · 技术社区  · 14 年前

    NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil];
    

    我要对象的索引按升序排列。这里,因为最小值的索引是3,所以索引应该是:3,2,4,1,5,0或者类似的。

    有什么想法吗?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Jonah    14 年前

    //Create a mutable array of the indexes in the myArray (just a list from 0...n)
    
    NSMutableArray *indexes = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < myArray.count; i++){
        [indexes addObject: [NSNumber numberWithInteger:i]];
    }
    
    //Create a dictionary with myArray as the objects and the indexes as the keys
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjects:myArray forKeys:indexes];
    
    //Create an array of myArray's keys, in the order they would be in if they were sorted by the values 
    NSArray *sorted = [tempDictionary keysSortedByValueUsingSelector: @selector(compare:)];
    
        2
  •  1
  •   Max Seelemann    14 年前

    indexOfObject:

    NSArray *sorted = [myArray sortedArrayUsingSelector: @selector(compare:)];
    NSMutableArray *indices = [NSMutableArray array];
    for (id object in myArray)
      [indices addObject: [NSNumber numberWithInteger: [sorted indexOfObject: object]]];
    

    (我脑子里想不出来,希望这能奏效。)

        3
  •  1
  •   milanjansari    14 年前

    你也可以使用下面的代码,希望对你有用,

        NSSortDescriptor *_lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@"" ascending:YES];
    NSArray *_lastArray = [NSArray arrayWithObject:_lastDescriptor];
    
    
    firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingDescriptors:_lastArray];
    //firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *eachlastIndex in firstCharacterArray)
    {
        NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@""
                                                                       ascending:YES];
        //selector:@selector(localizedCaseInsensitiveCompare:)] ;
        NSArray *descriptorslast = [NSArray arrayWithObject:lastDescriptor];
        [[nameIndexesDictionary objectForKey:eachlastIndex] sortUsingDescriptors:descriptorslast];
        [lastDescriptor release];
    }