2013-04-24 82 views
0

在Xcode中,我试图创建一个图形,其中有一些点(X,Y)由用户给出。用户可以选择他或她想要在图上绘制多少点。我已经将X轴点存储在一个NSMutableArray中,并且Y轴指向一个NSMutableArray,但现在我需要将这些点按升序排序,以便在具有相同x或y轴绘图的两个点时可以修复图形的错误。 NSMutableArrays包含基元int。我需要做的一个例子是,如果我给4坐标轴的其中一个轴,如4,8,5,3我需要将数组排序到3,4,5,8iphone - 如何排序一个NSMutableArray升序?

代码下面不包括图形生成,因为它相当长

感谢您的帮助! -

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

} 

回答

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:x坐标]。和 [yCoordArray addObject:yCoordinate];在循环中