Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 564
Mike Khan Avatar asked Feb 06 '12 16:02

Mike Khan


3 Answers

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.

like image 55
Jason Coco Avatar answered Nov 10 '22 14:11

Jason Coco


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

like image 25
jack Avatar answered Nov 10 '22 16:11

jack


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);
like image 2
Shunmugaraj Avatar answered Nov 10 '22 14:11

Shunmugaraj