以升序排列的数组中不失指数的Objective-C [英] Sorting an array in ascending order without losing the index Objective-C
问题描述
我有实例的阵列,
Array {
3.0 at Index 0
2.0 at Index 1
3.5 at Index 2
1.0 at Index 4
}
我想排序得到它以升序没有摆在首位丢失索引,这样,
I would like to get sort it in ascending order without losing the index in the first place, like this,
Array {
1.0 at Index 4
2.0 at Index 1
3.0 at Index 0
3.5 at Index 2
}
当我使用这个数组排序,
When I sort the array using this,
NSArray *sortedArray = [hArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
[knnRecog sortUsingDescriptors:[NSArray arrayWithObject:sortAsc]];
我失去了指数。有谁知道一种方法preserve排序后数组的索引?谢谢
I lose the index. Does anyone know a way to preserve the index after sorting the array? Thanks
推荐答案
您可以做你需要与更改您的基础数据结构排序。考虑使用数组的数组,例如:
You can do the sorting you require with a change to your underlying data structure. Consider using an array of arrays, e.g.:
{
{3.0, Index 0},
{2.0, Index 1},
{3.5, Index 2},
{1.0, Index 4}
}
和给定分选功能:
NSComparisonResult customCompareFunction(NSArray* first, NSArray* second, void* context)
{
id firstValue = [first objectAtIndex:0];
id secondValue = [second objectAtIndex:0];
return [firstValue compare:secondValue];
}
您可以像这样排序是:
NSArray* myArray = [NSArray arrayWithObjects:
[NSArray arrayWithObjects:
[NSNumber numberWithFloat:3.0f],
[NSNumber numberWithInt:0], nil],
[NSArray arrayWithObjects:
[NSNumber numberWithFloat:2.0f],
[NSNumber numberWithInt:1], nil],
[NSArray arrayWithObjects:
[NSNumber numberWithFloat:3.5f],
[NSNumber numberWithInt:2], nil],
[NSArray arrayWithObjects:
[NSNumber numberWithFloat:1.0f],
[NSNumber numberWithInt:4], nil]];
NSArray* sortedArray = [myArray sortedArrayUsingFunction:customCompareFunction context:NULL];
NSLog(@"Sorted array: %@", sortedArray);
它打印:
排序数组:(
(
1,
4
)
(
2,
1
)
(
3,
0
)
(
3.5,
2
)
)
Sorted array: ( ( 1, 4 ), ( 2, 1 ), ( 3, 0 ), ( 3.5, 2 ) )
这篇关于以升序排列的数组中不失指数的Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!