【问题标题】:Sorting an array in ascending order without losing the index Objective-C在不丢失索引的情况下按升序对数组进行排序 Objective-C
【发布时间】:2010-03-21 22:39:55
【问题描述】:

例如,我有一个数组,

    Array {
    3.0 at Index 0
    2.0 at Index 1
    3.5 at Index 2
    1.0 at Index 4
}

我想在不丢失索引的情况下按升序排序,就像这样,

    Array {
    1.0 at Index 4
    2.0 at Index 1
    3.0 at Index 0
    3.5 at Index 2
}

当我使用这个对数组进行排序时,

NSArray *sortedArray = [hArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
[knnRecog sortUsingDescriptors:[NSArray arrayWithObject:sortAsc]];

我丢失了索引。有谁知道在对数组进行排序后保留索引的方法?谢谢

【问题讨论】:

  • 听起来您想在数组中存储一对值而不是单个值...

标签: iphone objective-c arrays sorting


【解决方案1】:

您可以通过更改基础数据结构来进行所需的排序。考虑使用数组数组,例如:

{ {3.0,索引 0}, {2.0,索引 1}, {3.5,索引 2}, {1.0,索引 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 ) )

【讨论】:

    【解决方案2】:

    根据定义,您不能对数组进行排序并保留初始索引,因为排序只不过是交换索引以产生新的排序顺序。排序总是会改变索引。

    听起来您实际上想要做的是将初始数组的索引转换为数据,然后将其与初始数组的数据一起存储。

    如果是这样,那么您需要一个字典数组。字典应该将原始字典的单个索引与该索引处的值相关联:

    NSDictionary *anElement=[NSDictionary dictionaryWithObject:[intialArray objectAtIndex:i] forKey:[NSNumber numberWithInt:i]];
    

    然后将每个字典添加到一个数组中以存储它们。然后,您可以根据需要对该数组进行排序(使用字典的谓词),而不会丢失原始数组中的关系。

    【讨论】:

    • +1 字典数组是实现这一目标的正确方法。需要几分钟才能搞定,但这是值得的。然后尝试一系列字典数组!...
    猜你喜欢
    • 2016-04-24
    • 2016-02-20
    • 2020-11-12
    • 1970-01-01
    • 2018-11-16
    • 2023-03-28
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多