Gypsa
Gypsa

Reputation: 11314

Sorting Array based on numbers

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

Upvotes: 0

Views: 599

Answers (2)

visakh7
visakh7

Reputation: 26400

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

Upvotes: 2

dreamlax
dreamlax

Reputation: 95355

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

Upvotes: 2

Related Questions