-1

我正在将以下代码从 C 转换为 Obj-C C 代码行在下面注释并替换为 Obj-C ,但我在结果中有问题排序无法正常工作这里是代码之后的结果如果有人可以帮助PLZ

-(IBAction)clicked_insertsort:(id)sender{

    NSMutableArray  *iarray = [[NSMutableArray alloc]initWithArray:garr];
    int n = [iarray count]  ;
    NSLog(@"%@",iarray);

    int i,j,x;

     for(i=1;i<=n-1;i++)  

     {  
     j=i;  

     //x=a[i]; 
    x=[[iarray objectAtIndex:(NSUInteger)i]intValue];    

     //while(a[j-1]>x && j>0)  
     while (j>0 &&[[iarray objectAtIndex:(NSUInteger)j-1]intValue] >x)


     {  

     //a[j]=a[j-1];
    [iarray replaceObjectAtIndex: (j) withObject: [iarray objectAtIndex: (j-1)]];
     j=j-1;  
     }  

    // a[j]=x;  
    [[iarray objectAtIndex:(NSUInteger)j]intValue] == x; 

     }
    NSLog(@"%@",iarray);
}

排序前

[Session started at 2012-09-12 02:13:43 +0300.]
2012-09-12 02:13:49.127 sort_alg[1748:207] (
43,
18,
15,
135,
37,
81,
157,
166,
117,
110

)

and after sort
2012-09-12 02:13:49.130 sort_alg[1748:207] (
43,
43,
43,
43,
135,
135,
135,
135,
157,
166

)

4

2 回答 2

3

这没有做你认为它正在做的事情:

[[iarray objectAtIndex:(NSUInteger)j]intValue] == x; 

它在 index 处获取对象的 intValue ,j然后与 进行比较x,结果没有做任何事情。

您应该阅读文档NSArray并使用内置的排序方法。

于 2012-09-11T23:52:35.630 回答
2

要设置(替换)数组的元素,您首先要执行以下操作:

//a[j]=a[j-1];
[iarray replaceObjectAtIndex: (j) withObject: [iarray objectAtIndex: (j-1)]];

然后由于某种原因,当您下次想做类似的事情时,您可以尝试:

// a[j]=x;  
[[iarray objectAtIndex:(NSUInteger)j]intValue] == x;

您是否添加了==以消除编译器错误?

第一种方法是正确的 - 您需要调用一个方法来设置(替换)数组中的元素。

现在你知道答案了...

于 2012-09-12T00:16:51.207 回答