Jordan Jordan - 4 months ago 56
Objective-C Question

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"];

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;

@implementation NSArray (Statistics)

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