【问题标题】:Objective C: Sort Two Dimensional Array目标 C:对二维数组进行排序
【发布时间】:2012-12-20 21:11:18
【问题描述】:

我有一个数组数组。包含数组的第一个元素都是 NSDate 对象。我想按从最近到最少的顺序对包含数组的数组进行排序。出于某种原因,以下排序算法会导致无限循环。谁能帮我吗?谢谢。

最佳...SL

//array is the array containing all of the other arrays(that have NSDates as their first elements)
//temp is the new array being added to the end of the array, to later be sorted into the correct position.

[array addObject:temp];    
NSMutableArray *tempArray;

for (int i=0; i<[array count]; i++) 
{
    NSDate *session1, *session2;
    session1 = [[array objectAtIndex:i] objectAtIndex:0];
    session2 = [[array objectAtIndex:[array count]-1] objectAtIndex:0];

    if([session1 compare:session2] == NSOrderedDescending)
{
        tempArray = [array objectAtIndex:i];
        [array insertObject:[array objectAtIndex:[array count]-1] atIndex:i];
        [array insertObject:tempArray atIndex:[array count]-1];
    }
}

【问题讨论】:

    标签: ios sorting nsdate


    【解决方案1】:

    这会导致无限循环,因为在每一步中,您都会向数组中插入另外两个值。因此,您的数组的增长速度比您遍历它的速度快。我假设您打算交换值。

    无论如何,更简单、更高效的排序是使用内置的排序功能:

    // NSArray *sortedArray, with the unsorted 'array' pulled from some other instance
    sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
        return [[b objectAtIndex:0] compare:[a objectAtIndex:0]];
    }];
    

    【讨论】:

    • 非常感谢凯文。我不知道这种内置的排序功能。这对我帮助很大。
    【解决方案2】:

    如果array 是可变的并且您想对其进行排序:

    [array sortUsingComparator:^(id a, id b) {
        return [b[0] compare:a[0]];
    }];
    

    如果array 是不可变的,或者您想不理会它并制作一个排序副本:

    NSArray *sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
        return [b[0] compare:a[0]];
    }];
    

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 2011-02-17
      • 2019-05-17
      • 2015-01-30
      • 2012-12-15
      • 2018-05-14
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多