2013-06-24 67 views
2

我有一個CGPoint數組,並且希望根據離外部點最近的距離對它進行排序。我做了以下,但它返回不正確的結果。根據外部點對CGPoint數組進行排序

NSArray *sortedArray = [self.availableRenderPoints sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) 
{ 
    CGPoint p1 = [obj1 CGPointValue]; 
    CGPoint p2 = [obj2 CGPointValue]; 

    CGFloat distance1 = ccpDistance(startPoint, p1); 
    CGFloat distance2 = ccpDistance(startPoint, p2); 

    if (distance1 <= distance2) return p1.y < p2.y; 
    if (distance2 <= distance1) return p2.y < p1.y; 

    return p1.x < p2.x; 
}]; 

這怎麼能根據距離startPoint最近的距離排序?

回答

5

它不應該只是

NSArray *sortedArray = [self.availableRenderPoints sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) 
{ 
    CGPoint p1 = [obj1 CGPointValue]; 
    CGPoint p2 = [obj2 CGPointValue]; 

    CGFloat distance1 = ccpDistance(startPoint, p1); 
    CGFloat distance2 = ccpDistance(startPoint, p2); 

    if (distance1 < distance2) return NSOrderedAscending; 
    if (distance2 < distance1) return NSOrderedDescending; 

    return NSOrderedSame; 
}]; 

+0

應該可能只是'<(不是'<=') – Wain

+0

@ Wain:是的,愚蠢的錯誤,更正了(謝謝!) –

0

馬丁R的答案看起來不錯,但使用ccpDistance意味着採取平方根,這是不必要的。您可以通過比較平方距離獲得更好的性能:

NSArray *sortedArray = [self.availableRenderPoints sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) { 
    CGPoint p1 = [obj1 CGPointValue]; 
    CGPoint p2 = [obj2 CGPointValue]; 

    CGFloat squaredDistance1 = ccpLengthSQ(ccpSub(p1, startPoint)); 
    CGFloat squaredDistance2 = ccpLengthSQ(ccpSub(p2, startPoint)); 

    // Sort by nearness to startPoint. 
    // If equally near, sort by Y coordinate. 
    // If equal Y coordinate, sort by X coordinate. 
    return 
     distance1 < distance2 ? NSOrderedAscending 
     : distance2 > distance1 ? NSOrderedDescending 
     : p1.y < p2.y ? NSOrderedAscending 
     : p2.y < p1.y ? NSOrderedDescending 
     : p1.x < p2.x ? NSOrderedAscending 
     : p2.x < p1.x ? NSOrderedDescending 
     : NSOrderedSame; 
}]; 

在另一方面,如果你的陣列小或平方根是速度不夠快,避免了平方根可能不會作出明顯的區別。

相關問題