To answer your subqueries in the comments:
Do you always need to sort in ascending order? - NSOrderedAscending and NSOrderedDescending are simply symbolic here, you can think of them as an “object before an argument” and “an object comes after an argument” in sort order. For instance. if you save the NSNumber array, then "1 compareTo: 2" should return NSOrderedAscending if you want to sort with increasing value, and NSOrderedDescending if you want to sort with decreasing value.
How do you sort multiple keys? - Any sorting algorithm should only know if there is one element before, after, or at the same position as another. How you determine what is up to you. To use two sort keys, then in the pseudo-code the algorithm:
To compare item1 and item2 order = [item1.key1 compareTo:item2.key1]; if (order == NSOrderedSame) order = [item1.key2 compareTo:item2.key2]; return order
If necessary, increase the number of keys or more complex comparisons.
Follow the comments:
Sorry, but the provided algorithm performs 2-key sorting, and in general, combining keys may not be wasteful.
In English, sorting by two keys is as follows: first, compare the first key of each object if they are not equal, and then return their order. If they compare the same ones, then go and compare the second key of each object and return their order.
This is exactly what pseudo code does above.
Combining multiple keys is problematic for several reasons:
You must combine them with a delimiter that cannot happen in keys. As a simple example, consider sorting by first name, last name, when you have two people “jack yolander” and “jacky olander” - naive joining produces a “jack-linlander” for both, and they will sort the same way. Thus, you need a delimiter that cannot be found in any of the keys.
If the keys are of different types, for example. string and number, you end up converting them all into strings to combine — wasteful and possibly even inaccurate.
Just combining them is useless - you generate objects that you do not need.
Etc. Just compare the keys in pairs until you find two that are different or fall into the last pair. Works for any number of keys of any type and is not wasteful.
source share