Sort Array of CGPoints

arrays, cgpoint, nsarray, objective-c, sorting

Solution

After the correct comment by Chuck, I've updated the answer using the sortUsingComparator method:

Here is the complete code with sample data:

First we generate 100 random values that we enter to the Array:

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

and here is the actual code to sort the array:

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

finally we can verify that the array was sorted, by printing it:

NSLog(@"%@",testArray);

Problem

I am trying to figure out what the fastest/cleanest way to sort an array of CGPoints would be. I think I could achieve this using loops but that might not be the fastest and I hope it isn't the cleanest way. I would like to take an array of random CGPoints and sort them say by smallest x coordinate to largest, or smallest x and y coordinate to largest.

Original source