3

我正在尝试在下面显示的代码中使用 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);   
}
4

2 回答 2

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);   
}
于 2012-07-17T12:22:32.300 回答
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);
}

运行代码并查看结果。

于 2014-02-18T15:38:31.167 回答