Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insertion sort algorithm in Objective-C to implement in iphone

I am trying to sort 15 random numbers using Objective-C in the code shown below. The code is not working as planned. I took the concept from the the insertion sort C code. The 15 random numbers are generating properly but the sort is not working.

C code:

int i, j, index;
for (i = 1; i < array_size; ++i)
{
  index = a[i];
  for (j = i; j > 0 && a[j-1] > index; j--)
    a[j] = a[j-1];

  a[j] = index;
}

Objective-C code:

-(IBAction)clicked_insertsort:(id)sender
{
  NSMutableArray *array = [NSMutableArray array];
  for (int x = 0; x < 15; x++) 
  {
    [array addObject: [NSNumber numberWithInt: arc4random()%200]];
  }
  NSLog(@"%@",array);
  {
    int i, j;
    id index;
    for (i = 1; i < 15; ++i)
    {
      index = [array objectAtIndex:(NSUInteger)i]; //   a[i];
      for (j = i; j > 0 && [array objectAtIndex:(NSUInteger)j-1] > index; j--)
        [array replaceObjectAtIndex: (j) withObject: [array objectAtIndex: (j-1)]];

      [array objectAtIndex:(NSUInteger)j] == index ;
    }
  }
  NSLog(@"%@",array);   
}
like image 248
Oracle Oracle Avatar asked Jan 27 '26 08:01

Oracle Oracle


1 Answers

You are comparing pointers, which is just sorting your array by the memory addresses of your objects, not their actual value.

index = [array objectAtIndex:(NSUInteger)i]; //   a[i];
[array objectAtIndex:(NSUInteger)j-1] > index

You need to get the primitive integer value of the NSNumber:

[NSNumber numberWithInt:20] != 20; // This is wrong.
[[NSNumber numberWithInt:20] intValue] == 20; // This is correct.

Here's your code, with revisions:

-(IBAction)clicked_insertsort:(id)sender
{
  NSMutableArray *array = [NSMutableArray array];
  for (int x = 0; x < 15; x++) 
  {
    [array addObject: [NSNumber numberWithInt: arc4random()%200]];
  }
  NSLog(@"%@",array);
  {
    int i, j;
    id index;
    for (i = 1; i < 15; ++i)
    {
      index = [[array objectAtIndex:(NSUInteger)i] intValue]; //   a[i];
      for (j = i; j > 0 && [[array objectAtIndex:(NSUInteger)j-1] intValue] > index; j--)
        [array replaceObjectAtIndex: (j) withObject: [array objectAtIndex: (j-1)]];

      [[array objectAtIndex:(NSUInteger)j] intValue] == index ;
    }
  }
  NSLog(@"%@",array);   
}
like image 61
bigkm Avatar answered Jan 30 '26 00:01

bigkm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!