views:

46

answers:

2

Hi I am new to iPhone. What I am doing is sorting the array of images; that array consists of 22 elements. I am writing the code for that:

NSMutableArray *images2 = [[NSMutableArray alloc] initWithArray:images]
int n=22;
for (int i=0;i<n;i++){

    for (int j=1;j<n-i;j++){
        if(count[j-1]>count[j]){
            int t = count[j-1]
            count[j-1] = count[j]
            count[j] =t ;

            NSString *tempimage = [images objectAtIndex:j-1];
            [images2 replaceobjectAtIndex:j-1 withobject:[image2 objectAtIndex:j]];
            [images2 replaceobjectAtIndex:j withobject:tempimage];
        }
    }
}
images = [[NSMutableArray alloc] initWithArray:images2];

It sorts finely but at the end it replaces 21st image. What is the wrong in this? If there are any mistakes please post the correct code. What I need is to replace first image to last and second image to first.

+1  A: 

Solution to your problem: don't implement sorting yourself, let the framework do it for you. NSMutableArray has a number of sorting methods that will do all this stuff for you. If you can clarify a few points (see the comments on your question) we can help you construct the proper sorting method call.

– exchangeObjectAtIndex:withObjectAtIndex:
– sortUsingDescriptors:
– sortUsingComparator:
– sortWithOptions:usingComparator:
– sortUsingFunction:context:
– sortUsingSelector:
kubi
thanks it working but i write it in -(IBAction)buttonclick:(id)senderso it calls only one time how can i change it for everytime i tried [self buttonclick:(id)sender]; but it gives error how can i solve this pls help me
MaheshBabu
A: 

As others have mentioned, you should just get the framework to do the sorting for you. It will do so much more efficiently than the code above.

However, if you're wondering what's wrong with your sorting algorithm, I think you're missing an outer while loop to check whether another pass is needed before the array is sorted. It is bubble sort you're trying to implement, right?

David