1

我正在尝试使用 Cocoa 类进行冒泡排序,但我发现了一些问题。这是代码:

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array=[[NSMutableArray alloc] init];

int a,b;
for (int i=0;i<10;i++) {
    int newElement=rand()%100;
    [array addObject:[NSString stringWithFormat:@"%d",newElement]]; 
    NSLog(@"%i %@",i,[array objectAtIndex:i]);
}
[array addObject:[NSNull null]];

/*for (int a=1;a<10;a++){ */
//===Problem exact in this place
    for (int i=9;i>=1;i--) {
        NSNumber *tmp1=[array objectAtIndex:i]; //9
        NSNumber *tmp2=[array objectAtIndex:i-1]; //8
        if ([[array objectAtIndex:i] compare:[array objectAtIndex:i-1]]==NSOrderedAscending) { //if ([obj1 integerValue] > [obj2 integerValue]) this is -NSOrderedDescending;   
            [tmp1 retain];
            [array replaceObjectAtIndex:i-1 withObject:tmp1];
            [array replaceObjectAtIndex:i withObject:tmp2];
            [tmp1 release];
        }

    }

`NSLog(@"\n==SORTED==\n"); 
for (int i=0;i<10;i++) NSLog(@"%i %@",i,[array objectAtIndex:i]);`

所以在终端的输出中我看到了这个:

==未排序==

7 49 73 58 30 72 44 78 23 9

==排序==

23 7 49 73 58 30 72 44 78 9

我不明白为什么它不是从索引 9 开始?正如我所看到的,它从索引 8 开始排序(取整数 23)并转到索引 1。但是当他在索引 1 处遇到整数 7 时,为什么它用整数 23 替换,它不对应于 for() 的循环条件? ??.. 在没有类和 OOP 的 C++ 上也完全相同的算法效果很好,所以我猜那里的算法是正确的。请大家帮助理解这一点,我花了半天的时间:)) 非常感谢您的回答。

4

1 回答 1

3
  1. 您只进行了一次冒泡排序,这不足以对数组进行完全排序。
  2. 你的数组充满了字符串,而不是数字,所以“9”在“78”之后,就像“z”在“xy”之后一样。
于 2012-02-07T15:55:32.603 回答