【问题标题】:Iphone - How do you sort an NSMutableArray into ascending order?Iphone - 你如何按升序对 NSMutableArray 进行排序?
【发布时间】:2013-04-24 08:20:18
【问题描述】:

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

}

【问题讨论】:

    标签: nsmutablearray nsarray int


    【解决方案1】:

    在研究了一段时间后,我想知道是否有人在尝试同样的事情

    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];在循环中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 2011-06-26
      相关资源
      最近更新 更多