简体   繁体   English

目标C:对二维数组进行排序

[英]Objective C: Sort Two Dimensional Array

I have an array of arrays. 我有一个数组数组。 The contained array's first elements are all NSDate objects. 包含的数组的第一个元素都是NSDate对象。 I would like to sort the array containing the arrays in order from most recent to least. 我想按从最新到最少的顺序对包含数组的数组进行排序。 For some reason, the below sorting algorithm results in an infinite loop. 由于某种原因,下面的排序算法会导致无限循环。 Can anyone help me out? 谁能帮我吗? Thank you. 谢谢。

Best...SL 最好... 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];
    }
}

This results in an infinite loop because, in every step, you're inserting two more values into the array. 这将导致无限循环,因为在每一步中,您都要在数组中插入两个以上的值。 Thus your array is growing faster than you are traversing it. 因此,数组的增长速度比遍历数组的速度快。 I'm assuming you meant to swap the values. 我假设您打算交换值。

In any case, a much simpler and more efficient sort is to use the built-in sorting capabilities: 无论如何,一种更简单,更有效的排序方式是使用内置的排序功能:

// 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]];
}];

If array is mutable and you want to sort it in place: 如果array是可变的,并且您想对其进行排序:

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

If array is immutable or you want to leave it alone and make a sorted copy: 如果array是不可变的,或者您想让它保持不变并进行排序,则:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM