2016-12-07 207 views
2

我想排序数字升序排列,包括它们的索引,这里我已经实现了这样的排序。使用索引进行数字排序

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

喜欢目标在索引位置..排序@ Anbu.Karthik –

+3

对不起,这并没有使它更清晰。你想要通过2个键,一个值和索引来排序数组的数组?你想添加一个索引值到你的排序结果?如果你想添加一个索引值,该索引值是如何计算的?只有你知道你想要达到的目标,而且你没有很好地解释它。 –

回答

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); 
+0

我认为用户需要旧索引(索引之前排序)。 – Mahesh

+0

编辑我的答案 –

+0

谢谢@ MaratIbragimov为我的要求工作 –

-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); 

}

+0

非常低效的做法。另外,如果价格与另一个价格相同,则会返回两次相同的索引。 –

+0

以排序数组为参数,价格数组包含未排序,这意味着你更好地理解,在传递参数排序价格数组之前,然后传递它。没有人在这里做勺饲料,你应该明白代码。我提到了清晰排序的数组。根据问题要求我做得最好。 – Pavankumar

相关问题