is there a method to get the Max and Min of an NSMutableArray
Asked Answered
T

4

15

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

Tackle answered 6/2, 2012 at 16:27 Comment(0)
B
46

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.

Boiardo answered 6/2, 2012 at 16:41 Comment(3)
What does the valueForKeyPath function do? I have been looking for documentation on it but I can't find anything in either NSArray or NSMutableArray. I want to know what the string that is passed to it is and what the format of it should be.Tackle
@MikeKhan It's not a method defined on NSArray. It's defined in the NSKeyValueCoding protocol which NSObject implements. You can find the documentation here: developer.apple.com/library/ios/#documentation/Cocoa/Reference/…Boiardo
does apple always use @ in the string literal for Keys?Bedrabble
S
2

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).

Sieve answered 28/9, 2012 at 22:52 Comment(0)
E
2
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);
Equal answered 4/4, 2014 at 5:49 Comment(0)
R
1

If you want to get max value in integer use this:-

int max = [[array valueForKeyPath:@"@max.intValue"] intValue];

If you want to get max value in NSNumber use this:-

NSNumber * max = [array valueForKeyPath:@"@max.intValue"];
Rabia answered 30/5, 2015 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.