0

I've written the function below to Sort(Bubble) an Array of objects according to the Max GPA.

Please note that tmp is an object of class Student which includes ( Name , age , GPA ),there's another loop to print the result.

But , it's not Sorting ( Not Functional),No erros , just not working, please Assist.... i.e : output : Result not sorted

+(void) SortAndPrintBubble:(NSMutableArray *) tosort{

    Student * tmp = [Student new];
    for (int i = [tosort count] - 1; i >=0; i--) {

        for (int j =1; j<=i; j++) {
            if ([[tosort objectAtIndex:(j-1)] GetGPA] > [[tosort objectAtIndex:j] GetGPA]) {
                tmp = [tosort objectAtIndex:(j-1)];
                [tosort insertObject:(id)[tosort objectAtIndex:(j-1)] atIndex:(NSUInteger)j];
                [tosort replaceObjectAtIndex:j withObject:(id)tmp];
            }
        }
mohamed salem
  • 77
  • 2
  • 9

2 Answers2

1

You could simply write a method for your Student class, to compare GPAs,

-(NSComparisonResult) compareGPA:(Student*)otherStudent;

then you can simply sort the NSMutableArray (assuming it is an array full of Student objects) by calling

[tosort sortUsingSelector:@selector(compareGPA:)];

you can also use blocks if you target iOS 4+, with the method

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context

This SO post goes into the detail of available options.

Community
  • 1
  • 1
jbat100
  • 16,757
  • 4
  • 45
  • 70
0

You shouldn't be using insertObject:atIndex:. Use replaceObjectAtIndex:withObject: in both lines.

And the first of the two replaceObject... calls should use objectAtIndex:j, not j-1, and set the value at index j-1, not j.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • I found that with, replaceObjectAtIndex:withObject , I'll not be able to set the value at specific index. – mohamed salem Nov 03 '11 at 23:53
  • Shall i use : (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2 , instead ?? – mohamed salem Nov 03 '11 at 23:53
  • replaceObjectAtIndex should work. exchange would "kill two birds with one stone", though. – Hot Licks Nov 04 '11 at 00:29
  • So the first of the two replaceObject should look like that : [tosort replaceObjectAtIndex:j withObject:(id)[tosort OjectAtIndex:j-1]]; ? – mohamed salem Nov 04 '11 at 00:46
  • You've saved the value from slot j-1 into tmp. So in the slot from which you got that saved value you want to store the value from slot j. Then store the saved value into slot j. That accomplishes the swap. – Hot Licks Nov 04 '11 at 01:34