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!!
Asked
Active
Viewed 598 times
0
-
2You don't need to sort an array to find the maximum value! – occulus Apr 06 '11 at 12:05
-
@Jen - I suggest using a Quick Sort Algorithm. – Security Hound Apr 06 '11 at 12:06
-
1You need to give more info in your question. What sort of array? A plain C style array? Objective C style array? Is this homework btw? – occulus Apr 06 '11 at 12:07
-
1@Ramhound Why use quicksort to find the maximum value? It'll take n log n time. Just scanning the array is linear n time. – occulus Apr 06 '11 at 12:08
-
1NSSortDescriptor *mySorter = [[NSSortDescriptor alloc] initWithKey:@"floatValue" ascending:NO]; [listItems sortUsingDescriptors:[NSArray arrayWithObject:mySorter]]; – vijay adhikari Apr 06 '11 at 12:35
2 Answers
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
-
-
2You can't store ints in an array. They are either NSStrings or NSNumbers. In either case you have to add "intValue" to the [yourArray...] calls. – Kalle Apr 06 '11 at 12:27
-
@Kalle fixed it. Some birdie tells me Jenifer didn't even test it prior to accepting. :P – Regexident Apr 13 '11 at 13:31
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