使用索引进行数字排序

时间:2016-12-07 12:56:29

标签: ios objective-c xcode

我想要排序数字升序,包括他们的索引,这里我实现了这样的排序。

PriceArray =      [
      " 93",
      " 112.8",
      " 138.45",
      " 127.25",
      " 117.25",
      " 114.45"
    ]

使用这个,

NSArray *myArray = [priceArray sortedArrayUsingDescriptors:
                            @[[NSSortDescriptor sortDescriptorWithKey:@"doubleValue"
                                                            ascending:YES]]];

排序后,这些数据就像

[
  " 93",
  " 112.8",
  " 114.45",
  " 117.25",
  " 127.25",
  "138.45"
]

但我想要排序数据,包括像

这样的索引
[
  [
    " 93",
    "0"
  ],
  [
    " 112.8",
    "1"
  ],
  [
    " 114.45",
    "5"
  ],
  [
    " 117.25",
    "4"
  ],
  [
    " 127.25",
    "3"
  ],
  [
    " 138.45",
    "2"
  ]
]

你能告诉我怎样才能实现这个目的?谢谢..

2 个答案:

答案 0 :(得分:3)

NSArray *priceArray =  @[
                   @" 93",
                   @" 112.8",
                   @" 138.45",
                   @" 127.25",
                   @" 117.25",
                   @" 114.45"
                   ];

NSMutableArray *output = [NSMutableArray new];

for(NSInteger i=0;i<[priceArray count];i++){

    NSArray *dataWithIndex = @[priceArray[i],@(i)];
    [output addObject:dataWithIndex];
}

NSArray *sorted = [output sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

    return [[obj1 firstObject] doubleValue]>[[obj2 firstObject] doubleValue];
}];
NSLog(@"%@",sorted);

答案 1 :(得分:-1)

-(void)getArrayWithIndex:(NSArray *)sortedArray {
NSMutableArray *desiredArray = [[NSMutableArray alloc]init];
for (NSString *str1 in sortedArray) {
    NSInteger index = 0;
    for (NSString *str2 in priceArray) {
        if ([str1 isEqualToString:str2]) {
            break;
        }else {
            index++;
        }
    }
    NSArray *tempArray = @[str1,[NSString stringWithFormat:@"%ld",(long)index]];
    [desiredArray addObject:tempArray];
}
NSLog(@"%@",desiredArray);

}