2012-07-17 46 views
2

我想在下面显示的代码中使用Objective-C对15个随机数进行排序。代码没有按计划运行。我从插入排序C代码中了解了这个概念。 15个随机数正在生成,但排序不起作用。Objective-C中的插入排序算法在iphone中实现

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); 
} 
+1

有没有特别的原因让你自己编写排序,而不是在'NSArray'上使用'sortedArrayUsing ...'方法之一?除非这是一项严格的要求,例如作业分配,否则很少有理由实施自己的分类。 – DPlusV 2012-07-17 10:10:19

+0

谢谢,是的,我需要使用上面的代码进行排序,而不是内部功能,看看需要多少时间才能执行某些算法 – 2012-07-17 10:13:31

+0

不成熟的优化或研究的乐趣/教育?无论如何,只有15个数字你不会得到任何可靠的数据(或性能问题)。 – 2012-07-17 11:36:02

回答

3

你是比较指针,这只是你的对象的内存地址排序的数组,而不是他们的实际价值。

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

运行代码并查看结果。