2012-12-20 64 views
1

我有一個數組數組。包含數組的第一個元素是所有NSDate對象。我想按從最近到最少的順序對包含數組的數組進行排序。出於某種原因,下面的排序算法會導致無限循環。誰能幫我嗎?謝謝。Objective C:排序二維數組

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

回答

5

這將導致一個無限循環,因爲在每一個步驟,你將兩個值到數組。因此,你的數組的增長速度比你遍歷它快。我假設你打算交換價值。

在任何情況下,更簡單,更高效的排序是使用內置的排序功能:

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

非常感謝凱文。我不知道這樣的內置分類功能。這對我非常有幫助。 – Skyler

+0

@robmayoff:恩,謝謝。不知道我怎麼沒有想到這一點。 –

3

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