Objective-C中的插入排序算法在iphone中实现

时间:2012-07-17 10:06:49

标签: objective-c nsarray

我正在尝试使用下面显示的代码中的Objective-C对15个随机数进行排序。代码未按计划运行。我从插入排序C代码中获取了这个概念。 15个随机数正在生成,但排序不起作用。

C代码:

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代码:

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

2 个答案:

答案 0 :(得分:4)

您正在比较指针,它只是按对象的内存地址对数组进行排序,而不是实际值。

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

您需要获取NSNumber的原始整数值:

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

这是您的代码,包含修订版:

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

答案 1 :(得分:0)

实际上问题是算法本身没有多大意义。

这一行:

[array objectAtIndex:(NSUInteger)j] == index ;

应该是:

[array replaceObjectAtIndex:j withObject:index]; //yes again

尝试这种方式,使用现代语法:

-(IBAction)clicked_insertsort:(id)sender
{
    NSMutableArray *array = [NSMutableArray array];
    for (int x = 0; x < 15; x++)
    {
        [array addObject: @(arc4random()%200)];
    }
    NSLog(@"%@",array);

    NSUInteger i, j;
    for (i = 1; i < 15; ++i)
    {
        NSNumber *current = array[i];
        for (j = i; j > 0 && [array[j-1] unsignedIntegerValue] > [current unsignedIntegerValue]; j--)
            array[j] = array[j-1];

        array[j] = current;
    }
    NSLog(@"%@",array);
}

运行代码并查看结果。