开发者

how to solve sorting problem

开发者 https://www.devze.com 2023-01-11 01:17 出处:网络
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:

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 = [im开发者_开发百科ages 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.


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:


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消