3

Possible Duplicates:
How to sort array having numbers as string in iPhone?
How Do I sort an NSMutable Array with NSNumbers in it?

I have a NSMutableArray with random order of numbers. I have to sort them in ascending and descending order? Is there any in built function for that and if no how it can be done. Array is like this:

arr = ["12","85","65","73","21","87","1","34","32"];

Community
  • 1
  • 1
Developer
  • 6,375
  • 12
  • 58
  • 92
  • What is the *type* of the array ? `NSArray` ? Or is it just a `C` array ? – Paul R Jul 08 '11 at 07:50
  • @Paul R: it is NSMutableArray – Developer Jul 08 '11 at 07:51
  • 2
    Please edit your question to include this clarification – Paul R Jul 08 '11 at 07:52
  • logic doesn't change with language......you can use bubble sort. – iAmitWagh Jul 08 '11 at 07:53
  • @iAmitWagh: In case you don't know it yet, Bubble Sort is among the worst sorting algorithms you can pick, it has a complexity of O(n^2) ! – DarkDust Jul 08 '11 at 08:08
  • @iAmitWagh: Also, depending on the language/API you might have access to some predefined (and optimized) sorting routines which is almost always to prefer over running your own implementation. The exception being you've read and understand Knuth vol. 3. – DarkDust Jul 08 '11 at 08:12

3 Answers3

5

Sorting NSMutableArray (based on key) which contains objects

First, you’ll need to create an NSSortDescriptor and tell it which key to sort the array on.

 NSSortDescriptor *lastNameSorter = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
[personList sortUsingDescriptors:[NSArray arrayWithObject:lastNameSorter]];

Hope this Full tutorial helps you.

Deeps
  • 4,399
  • 1
  • 26
  • 27
3

use sortUsingSelector instance method of class NSMutableArray.

use this line (But you need to use NSNumbers rather than string in case of numbers)

[myArray sortUsingSelector:@selector(compare:)];

It sort array in ascending order. for descending order add this line after above line.

myArray=[myArray reverseObjectEnumerator] allObjects];
Ishu
  • 12,797
  • 5
  • 35
  • 51
1

example code for your case:

NSArray *sortedArray; 

sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

you can develop a logic to sort your array in intsort method and pass it as parameter to above method.

there are many predefined methods like:

  • sortUsingDescriptors:
  • sortUsingComparator:
  • sortWithOptions:usingComparator:
  • sortUsingFunction:context:
  • sortUsingSelector:

follow developer.apple.com for api

good luck TNX

DarkDust
  • 90,870
  • 19
  • 190
  • 224
Dinakar
  • 1,198
  • 15
  • 37