我想制作一个演示应用程序,在那里我可以在代码中输入4个数字,然后按1,2,3的顺序排序,并为我NSLog
。有简单的算法或方法吗?
// Put code in your App's ViewController
@implementation Sorting_NumbersViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// CODE STARTS HERE
// This allocates and initializes the NSMutableArray
NSMutableArray *anArray = [[NSMutableArray alloc] init];
// These are where you enter your numbers
[anArray addObject:@"1"];
[anArray addObject:@"3"];
[anArray addObject:@"2"];
//This looks looks at the objects above and compares them with each-other
NSArray *sorted = [anArray sortedArrayUsingSelector:@selector(compare:)];
//This spits the result out in the console
NSLog(@"Ordered Numbers: %@", sorted);
}
NSMutableArray
有一些很棒的排序方法,如本文所述。
不幸的是,这不是一个给我代码网站-我们希望看到你自己付出一点努力!
正如Luke所写,NSMutableArray
中内置了一些很棒的排序方法。然而,如果你自己实现这些算法,你会学到更多。看看Bubble Sort。这是一种排序算法,应该能很好地为你完成这项任务,无论如何都是一件很好理解的事情。
编辑:查看此StackOverflow链接。我只是在谷歌上搜索了"对NSNumber
的NSMutableArray
进行排序",这是第一个点击。