我想製作一個演示應用程序,我可以在代碼中輸入4個數字,並按照1,2,3的順序對其進行排序,並將爲我編寫NSLog
。有一個簡單的算法或一種方法來做到這一點?Sorting Numbers Objective-C
回答
// 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);
}
@James方法比較:在數組中的NSNumbers上調用。 NSNumber在其接口中聲明該方法。他不能發佈比較方法的實現,因爲Apple寫了它。請參閱: - (NSComparisonResult)比較:(NSNumber *)otherNumber;從的NSNumber:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/index.html#//apple_ref/occ/instm/NSNumber/compare: –
正如Luke寫的,NSMutableArray
中有一些很好的排序方法。然而,如果你自己實現算法,你會學到更多。檢出Bubble Sort。這是一種排序算法,應該能很好地完成這項任務,無論如何理解它都是一件好事。
編輯:看看這個StackOverflow link。我真的只是GOOGLE上搜索「之類的NSNumber
的NSMutableArray
的」,這是第一次命中一個。
我會建議不要冒泡排序。這是更難比['合併sort']理解(http://en.wikipedia.org/wiki/Merge_sort)或['快速sort'(http://en.wikipedia.org/wiki/Quicksort) ,並且冒泡排序鼓勵你以儘可能最慢的方式排序。 – user1118321
@ user1118321這是一個公平點。仍然不是一件壞事,理解,艾莫。無論哪種方式,我覺得我的基本情緒,學習它是如何工作的在比賽中這點比能夠只讓一種語言的工作更有價值。 – James
*仍然存在。 – James
- 1. Sorting NSString of Numbers
- 2. Sorting Array,Sorting ArrayList,using Collections
- 3. Sorting QTreeWidget
- 4. Firebase Sorting
- 5. Datatable sorting
- 6. Sorting UITableView
- 7. Sorting HashMap
- 8. AppleScript:Finder Sorting
- 9. Sorting LinkedHashMap
- 10. Sorting Anagrams
- 11. mySQL:Physical Sorting
- 12. Sorting Headers
- 13. Sorting Columns
- 14. 在ObjectiveC中排序數組
- 15. NumberFormatter - ObjectiveC
- 16. PHP preg_replace only numbers
- 17. REGEX no numbers or()
- 18. Javascript leading numbers
- 19. Erlang和Big Numbers
- 20. SDL_ttf和Numbers(int)
- 21. python pattern matching numbers
- 22. ConcurrentDictionary on large numbers
- 23. Javascript Count numbers
- 24. input.gsub(numbers){| m |
- 25. PL/SQL NUMBERS ONLY
- 26. jQuery Count Numbers Up
- 27. Php RandomPick Numbers
- 28. UIDatePicker for week numbers
- 29. Textfield only with numbers
- 30. NSDecimalNumber round long numbers
你到目前爲止試過了什麼?你有沒有試過一些書籍教程來獲得基礎知識? – bryanmac
你很想學習Objective-C。首先,這是一種難得的技巧,這意味着當你是一個成年人找工作時,人們會願意爲你付出更多的錢。 :)但是你首先需要自己付出努力,那就意味着閱讀每本關於C,Objective-C和相關概念的書。 (哦,並且在高中和大學/大學,特別是代數學上儘可能多的數學課。是的,你會在現實世界中使用代數,我保證。) –
我讀了很多關於NSMutableArrays和其他Obective -C Documentaions並在發佈之前已經搜索了很多答案。 –