i am trying to implement the insertion sort algorithm using Obj-c i converted the commented lines below from C into Obj C , (hope they are correct if anybody can have a look and assist) but the application crashes with the following error Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘* -[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);
}
You should avoid casting your indexes to unsigned int. try it one at a time and which ever one changes the error to say -1 rather than 4294967295 is the index you are having a problem with
When j gets set to 0 you’re now going to be indexing into iarray at index -1, which when casted to an unsigned int is equal to 4294967295