Reputation: 3433
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.
Upvotes: 0
Views: 171
Reputation: 2861
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?
Upvotes: 0
Reputation: 49354
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:
Upvotes: 1