Iphone - 如何将NSMutableArray按升序排序?

时间:2013-04-24 08:20:18

标签: nsmutablearray nsarray int

在Xcode中,我试图制作一个图表,其中某些点(X,Y)由用户给出。用户可以选择他或她想要在图表上绘制多少点。我已将X轴点存储在NSMutableArray中,Y轴指向NSMutableArray,但现在我需要按升序对它们进行排序,以便在有两个具有相同x或y轴图的点时修复图形中的错误。 NSMutableArrays包含原始int。我需要做的一个例子是,如果给出其中一个轴的4个坐标,例如4,8,5,3我需要将数组分类为3,4,5,8

下面的代码不包括图表生成,因为它很长

感谢您的帮助! -

int userInputCount;

printf("How many coordinates would you like to plot? ");
scanf("%i", &userInputCount);
printf("\n");

NSMutableArray * xCoordArray = [[NSMutableArray alloc] init];
NSMutableArray * yCoordArray = [[NSMutableArray alloc] init];

for (int i = 1; i <= userInputCount; i++){
        int xCoord;
        int yCoord;

        printf("(%i) Enter coordinates [X,Y]: ", i);

        scanf("%i,%i", &xCoord, &yCoord);

        NSNumber *xCoordinate =  [[NSNumber alloc] initWithInt:xCoord];
        NSNumber *yCoordinate =  [[NSNumber alloc] initWithInt:yCoord];

        [xCoordArray addObject:xCoordinate];
        [yCoordArray addObject:yCoordinate];

}

1 个答案:

答案 0 :(得分:0)

经过一段时间的努力,我发现如果有人在尝试同样的事情

for (int j = 0; j < 2; j++){
            for (int i = 0; i < [yCoordArray count] - 1; i++){

                int yExchangeIntOne = [[yCoordArray objectAtIndex:i] intValue];
                int yExchangeIntTwo = [[yCoordArray objectAtIndex:i +1] intValue];
                if (yExchangeIntOne > yExchangeIntTwo){
                    [yCoordArray exchangeObjectAtIndex:i+1 withObjectAtIndex:i];
                    i = 0;
                }

                int xExchangeIntOne = [[xCoordArray objectAtIndex:i] intValue];
                int xExchangeIntTwo = [[xCoordArray objectAtIndex:i +1] intValue];
                if (xExchangeIntOne > xExchangeIntTwo){
                    [xCoordArray exchangeObjectAtIndex:i+1 withObjectAtIndex:i];
                    i = 0;
                }

            }
        }

这是正确的     [xCoordArray addObject:xCoordinate];和     [yCoordArray addObject:yCoordinate];在循环中