2016-12-07 209 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

相關問題