Jordan - 1 year ago 216

Objective-C Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
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
```