0

Hi I am trying to make it so that I can find and log the biggest object of an NSMutableArray. I have searched for this, but I have only seen it for an NSArray. This is the code I saw.

numbers = [numbers sortedArrayUsingSelector:@selector(compare:)];

float min = [numbers[0] floatValue]
float max = [[numbers lastObject] floatValue];

However, when I put that in, it doesn't work because I am using a mutable array. Thanks!

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • It should work just fine for a mutable array. However, it's an inefficient way to perform that task, if you don't need the array sorted for any other reason. Sort is O(n log n), but the function can be performed O(n) with a simple loop and two compare operations. – Hot Licks Jul 24 '14 at 03:17
  • 1
    Just do `[numbers sortUsingSelector:@selector(compare:)];`. This will sort `numbers` in place. – rmaddy Jul 24 '14 at 03:42
  • See also http://stackoverflow.com/questions/15931112/finding-the-smallest-and-biggest-value-in-nsarray-of-nsnumbers. – Martin R Jul 24 '14 at 04:42

1 Answers1

3

It works for mutable array.

NSArray *sortedNumbers = [numbers sortedArrayUsingSelector:@selector(compare:)];

float min = [sortedNumbers[0] floatValue]
float max = [[sortedNumbers lastObject] floatValue];
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • Just sort the mutable array in place. No need for the new array. – rmaddy Jul 24 '14 at 03:43
  • Thanks guys rmaddy gave me the answer. I just used [myArray sortUsingSelector:@selector(compare:)]; and then displayed the [myArray lastObject] to display the best score. Again Thanks! – user3754646 Jul 24 '14 at 16:08