目标C:排序二维数组 [英] Objective C: Sort Two Dimensional Array

查看:59
本文介绍了目标C:排序二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of arrays. The contained array's first elements are all NSDate objects. 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.

最好...... SL

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

这篇关于目标C:排序二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆