1

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.

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

2 Answers 2

6

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]];
}];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Kevin. I was not aware of such built in sorting capabilities. This helps me tremendously.
3

If array is mutable and you want to sort it in place:

[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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.