Is there a way in iOS for me to get the Max and Min values of an NSMutableArray of double numbers. I'm looking for an already existing method, not for me to sort the array my self. If there is a method for me build into the API for me to sort the array that would interest me too.
Thank you
If you wanted to simply get the min and max doubles:
NSNumber* min = [array valueForKeyPath:@"@min.self"];
NSNumber* max = [array valueForKeyPath:@"@max.self"];
If you wanted to simply sort them:
// the array is mutable, so we can sort inline
[array sortUsingSelector:@selector(compare:)];
The NSNumber
class will sort nicely just using compare:
, but if you need to do more complicated sorting, you can use the -sortUsingComparator:
method which takes a block to do the sorting. There are also methods on NSArray
which will return new arrays that are sorted, instead of modifying the current array. See the documentation for NSArray and NSMutableArray for more information.
Sorting is O(nlogn), so if you only want max and min once, please don't do sorting. The best way is to go through the array and compare one by one and that is linear, i.e. O(n).
NSMutableArray * array=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSLog(@"Array:%@",array);
int maxValue;
for (NSString * strMaxi in array) {
int currentValue=[strMaxi intValue];
if (currentValue > maxValue) {
maxValue=currentValue;
}
}
int miniValue;
for (NSString * strMini in array) {
int currentValue=[strMini intValue];
if (currentValue < miniValue) {
miniValue=currentValue;
}
}
NSLog(@"Maxi:%d",maxValue);
NSLog(@"Mani:%d",miniValue);
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