-1

以下のコードを C から Obj-C に変換しています。C コード行は以下にコメントされ、 Obj-C に置き換えられていますが、結果に問題があり、並べ替えが正しく機能していません。助けてください

-(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 に答える