Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the median value of NSNumbers in an NSArray?

I'm trying to calculate the median of a (small) set of NSNumbers in an NSArray. Every object in the NSArray is a NSNumber.

Here is what I'm trying, but it's not working:

NSNumber *median = [smallNSArray valueForKeyPath:@"@median.floatValue"];
like image 499
Jordan Avatar asked Jul 14 '10 20:07

Jordan


1 Answers

NSArray *sorted = [smallNSArray sortedArrayUsingSelector:@selector(compare:)];    // Sort the array by value
NSUInteger middle = [sorted count] / 2;                                           // Find the index of the middle element
NSNumber *median = [sorted objectAtIndex:middle];                                   // Get the middle element

You can get fancier. For example, the median of a set with an even number of numbers is technically the average of the middle two numbers. You could also wrap this up into a neat one-line method in a category on NSArray:

@interface NSArray (Statistics)
- (id)median;
@end

@implementation NSArray (Statistics)

- (id)median
{
    return [[self sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:[self count] / 2];
}

@end
like image 166
mipadi Avatar answered Sep 23 '22 06:09

mipadi