0

I am having an array that contains the values like 2,4,6 etc .Now I want to sort array to find the maximum value,I do not know how to do that. Please Help me. Thanks in advance!!

Gypsa
  • 11,230
  • 6
  • 44
  • 82

2 Answers2

2
NSinteger biggest = [[yourArray objectAtIndex:0] integerValue];
for(int i=1; i<[yourArray count]; i++) {
    NSinteger current = [[yourArray objectAtIndex:i] integerValue];
    if(current >= biggest) {
        biggest = current;
    }
}

this will give you the biggest element in the array.

UPDATE

As @occculus suggested you can try fast enumeration. Here is a reference How do I iterate over an NSArray?

FIX

Your code was both wrong (as reported by Kalle) and inefficient (redundant calls of objectAtIndex:). Fixed it, hope you don't mind.
Regexident

Community
  • 1
  • 1
visakh7
  • 26,380
  • 8
  • 55
  • 69
2

You can determine the highest value by looking at each value only once.

int highest = INT_MIN;

for (id elem in array)
{
    int current = [elem intValue];
    if (highest < current)
        highest = current;
}

If you want the array to be sorted anyway:

NSArray *sorted = [unsorted sortedArrayUsingSelector:@selector(compare:)];

int highest = [[sorted lastObject] intValue];
dreamlax
  • 93,976
  • 29
  • 161
  • 209