[英]Objective C: Sort Two Dimensional Array
我有一個數組數組。 包含的數組的第一個元素都是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];
}
}
這將導致無限循環,因為在每一步中,您都要在數組中插入兩個以上的值。 因此,數組的增長速度比遍歷數組的速度快。 我假設您打算交換值。
無論如何,一種更簡單,更有效的排序方式是使用內置的排序功能:
// 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]];
}];
如果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]];
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.