【问题标题】:insertion sort algorithm in objective c application crash目标c应用程序崩溃中的插入排序算法
【发布时间】:2012-09-11 22:53:48
【问题描述】:

我正在尝试使用 Obj-c 实现插入排序算法我将下面的注释行从 C 转换为 Obj C ,(如果有人可以查看和帮助,希望它们是正确的)但是应用程序崩溃并出现以下错误由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[NSMutableArray objectAtIndex:]: index 4294967295 beyond bounds [0 .. 9]”

-(IBAction)clicked_insertsort:(id)sender{

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

    int i,j,x,k;

     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 ([[iarray objectAtIndex:(NSUInteger)j-1]intValue] >x && j>0)


     {  

     //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);
}

【问题讨论】:

    标签: iphone objective-c xcode nsmutablearray


    【解决方案1】:

    您应该避免将索引转换为无符号整数。一次尝试一个,哪一个将错误更改为 -1 而不是 4294967295 是您遇到问题的索引

    当 j 设置为 0 时,您现在将在索引 -1 处对 iarray 进行索引,当转换为无符号整数时,它等于 4294967295

    【讨论】:

    • 它在你的while循环中,将顺序改为while(j>0 && [[iarray objectAtIndex:(NSUInteger)j-1]intValue] >x)
    • 你是对的,没有崩溃谢谢你能帮我解释一下为什么这里没有排序是结果数组之前和之后 [会话开始于 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) 2012-09-12 02:13:49.130 sort_alg[1748 :207] (43, 43, 43, 43, 135, 135, 135, 135, 157, 166)
    • 我在将数组从 c 转移到 obj c 时做错了什么,非常感谢
    • 您应该查看 NSMutableArray 中内置的排序函数的文档。如果您仍然遇到问题,请尝试在此处搜索您要使用的功能,或者如果您已经找不到,请提出新问题。不要忘记为遇到类似问题的其他人接受此答案
    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2016-04-24
    相关资源
    最近更新 更多