Pages

July 2, 2013

Min value in Array

I have a NSArray and I want to know the object with the minimum value.
Pretty straightforward with this useful function.


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

 @param arr Array to search in.
 @param outIndex Index of minimum value.
 @return Returns minimum value or -MAXFLOAT if something goes wrong.
 @see maxValueInArray:withIndex:

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



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

No comments:

Post a Comment