Possible Duplicate:
Sorting NSString values as if NSInteger using NSSortDescriptor
I have an Array that I fill with my NSMutableDictionary.. and I use this:
myArray =[[myDict allKeys]sortedArrayUsingSelector:@selector(IDONTKNOW:)];
AllKeys of myDicts are NSStrings... like 123.423 or 423.343... I need to sort the new myArray by incremental numbers.. 12.234 45.3343 522.533 5432.66 etc etc
What must insert in @selector to do this properly? Thanks
Java Arrays class provides the sort method which can be used to sort a string array. This method sorts an array according to the natural ordering of the elements in the ascending order.
A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation that uses Insertion Sort to sort the array.
Given an integer array with many duplicated elements, write an algorithm to efficiently sort it in linear time, where the order of equal elements doesn’t matter.
The idea is to: Iterate through the array once and store the number of occurrences of individual elements in a hash table. Sort the unique elements present in the hash table according to the natural ordering. Overwrite the input array with sorted elements depending on frequencies stored in the hash table.
You can use an NSSortDescriptor
and pass doubleValue
as the key.
//sfloats would be your [myDict allKeys]
NSArray *sfloats = @[ @"192.5235", @"235.4362", @"3.235", @"500.235", @"219.72" ];
NSArray *myArray = [sfloats sortedArrayUsingDescriptors:
@[[NSSortDescriptor sortDescriptorWithKey:@"doubleValue"
ascending:YES]]];
NSLog(@"Sorted: %@", myArray);
You can't direclty use sortedArrayUsingSelector:
. Use sortedArrayUsingComparator:
and implement a comparison block yourself.
Kinda like this q/a:
Changing the sort order of -[NSArray sortedArrayUsingComparator:]
(In fact, that Question's code can likely be copy/pasted into your code and it'll "just work" once you change it from integerValue
to doubleValue
for the four convert-string-to-number calls):
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
double n1 = [obj1 doubleValue];
double n2 = [obj2 doubleValue];
if (n1 > n2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (n1 < n2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With