2

我有一个 CGPoints 数组,想根据到外部点的最近距离对其进行排序。我已经完成了以下操作,但它返回了不正确的结果。

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 的最近距离对其进行排序?

4

2 回答 2

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

?

于 2013-06-24T16:49:47.697 回答
0

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

另一方面,如果您的数组很小或平方根足够快,那么避免平方根可能不会产生明显的差异。

于 2013-06-24T18:15:38.273 回答