排序CGPoints数组

时间:2012-05-22 19:04:14

标签: objective-c arrays nsarray sorting cgpoint

我试图弄清楚对CGPoints数组进行排序的最快/最干净的方法是什么。我想我可以使用循环实现这一点,但这可能不是最快的,我希望它不是最干净的方式。我想取一组随机CGPoints并按最小x坐标到最大,或最小x y坐标到最大值进行排序。

3 个答案:

答案 0 :(得分:8)

在Chuck的正确评论之后,我使用sortUsingComparator方法更新了答案:

以下是包含样本数据的完整代码:

首先,我们生成100个我们输入数组的随机值:

NSMutableArray *testArray = [[NSMutableArray alloc] initWithCapacity:100];
for (int i=0; i<100; i++) {
    CGPoint testPoint = CGPointMake(arc4random()%100, arc4random()%100);
    [testArray addObject:[NSValue valueWithCGPoint:testPoint]];
}

以下是对数组进行排序的实际代码:

[testArray sortUsingComparator:^(id firstObject, id secondObject) {
    CGPoint firstPoint = [firstObject CGPointValue];
    CGPoint secondPoint = [secondObject CGPointValue];
    return firstPoint.x>secondPoint.x;
}];

最后我们可以通过打印来验证数组是否已排序:

NSLog(@"%@",testArray);

答案 1 :(得分:3)

如果你只有一个简单的CGPoints数组,那么C qsort()函数可能是你最好的选择。像这样:

int compareXCoords(CGPoint *a, CGPoint *b) {
    return b->x - a->x;
}

// Later:

CGPoint points[100];
// initialize points somehow
qsort(points, 100, sizeof(CGPoint), compareXCoords);
// points is now sorted by the points' x coordinates

答案 2 :(得分:0)

根据我的评论,这是一个很好的解决方案,将它们插入NSMutableArray,保持您决定的排序。

你必须做这样的事情:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];

CGPoint candidate;
// Look for the position it has to be
int 0;
for (CGPoint point in array) {
    i++;
    // Compare candidate with current point
    // You have to define this condition, when point is greater than candidate
    if (point > candidate) {
        break;
    }
}
[array insertObjectAtIndex:i-1];

也许我的代码有一些错误,我现在无法检查它是否正确。

相关问题