Search code examples
objective-ccocoasortingbubble-sort

Bubble sort with Cocoa classes


I'm trying to make bubble sort using Cocoa classes, but I've found some problems. here is the code:

#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]);`

So in output in terminal i see this:

==UNSORTED==

7 49 73 58 30 72 44 78 23 9

==SORTED==

23 7 49 73 58 30 72 44 78 9

I cant' understand why does it not start from index 9? As I can see it start sorting from index 8 (taking integer 23) and goes to index 1. But when he meets integer 7 at index 1 why it replaces by integer 23, it's not corresponds to the condition of a circle for()???.. Also exact the same algorithm on C++ without classes and OOP stuff works great, so I guess an algorithm is correct there. Please guys help understand this, I spent a half of a day on it :)) Thanks a lot in advance for the answers.


Solution

    1. You're only doing a single pass of bubble-sort, which is insufficient to fully sort the array.
    2. Your array is full of strings, not numbers, so "9" comes after "78" just like "z" comes after "xy".