문제

CGPoints 배열을 정렬하는 가장 빠르게 / 깨끗한 방법이 무엇인지 알아 내려고합니다.나는 이것을 루프를 사용하여이를 달성 할 수 있지만 가장 빠르지 않을 수도 있고 나는 그것이 깨끗한 방법이 아니길 바란다.나는 무작위의 CGPoints의 배열을 가져 와서 가장 작은 x 좌표로 가장 큰 것 또는 가장 작은 x y coordinate에서 가장 큰 것으로 정렬하고 싶습니다.

도움이 되었습니까?

해결책

척에 의해 올바른 코멘트가 끝나면 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);
.

다른 팁

C qsort() 기능은 일반적으로 CGPoints 배열이있는 경우 최상의 베팅 일 것입니다.이와 같은 것 :

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
.

제 댓글에 따르면, 당신이 결정한 종류를 유지하는 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];
.

내 코드가 몇 가지 오류가 있으면 지금 정확한지 확인할 수 없습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top