Pages

July 1, 2013

Max value in Array

I have a NSArray and I want to know the object with the maximum value.
It's so easy with this useful Objective-C method.


/** Returns the maximum value and its index for the given array.

 @param arr Array to search in.
 @param outIndex Index of maximum value.
 @return Returns maximum value or -1 if something goes wrong.
 @see minValueInArray:withIndex:

 */
+ (CGFloat)maxValueInArray:(NSArray *)arr withIndex:(NSInteger *)outIndex {
    CGFloat max = -1;
    if ([arr count] > 0) {
        max = [[arr objectAtIndex:0] floatValue];
        for (NSInteger i=0; i<[arr count]; i++) {
            if ([[arr objectAtIndex:i] floatValue] > max) {
                max = [[arr objectAtIndex:i] floatValue];
                if (outIndex != NULL) {
                    *outIndex = i;
                }
            }
        }
    }
    return max;
}



Download the ready-for-use source file (.m) of Max value in Array

No comments:

Post a Comment