简体   繁体   English

如何解决分类问题

[英]how to solve sorting problem

Hi I am new to iPhone. 嗨,我是iPhone新手。 What I am doing is sorting the array of images; 我正在做的是对图像数组进行排序; that array consists of 22 elements. 该数组由22个元素组成。 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. 排序很好,但最后替换了第21张图片。 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. NSMutableArray有许多排序方法,可以为您完成所有这些工作。 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. 但是,如果您想知道排序算法出了什么问题,我认为您错过了一个外部while循环,以检查在对数组进行排序之前是否需要另一遍处理。 It is bubble sort you're trying to implement, right? 您正在尝试实施的是冒泡排序 ,对吧?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM