1

import

int main(int argc, const char * argv[]) {
    @autoreleasepool { 

        NSArray *arr = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12", nil];        
      arr = [arr sortedArrayUsingSelector:@selector(compare:options:)];
    }
    return 0;
}

The output is: 1,10,11,12,2,3,4,5,6,7,8,9

Can someone please help how to sort in ascending order.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
backbencher
  • 99
  • 2
  • 8
  • use Collections.Sort look in the API – ja08prat Jul 12 '17 at 20:10
  • Note that if you gave all of your 1 digit strings leading zeros your code would sort them into the correct order: `NSArray *array = @[@"12", @"07", @"10", @"03", @"04", @"05", @"06", @"01", @"08", @"09", @"02", @"11"];` – Duncan C Jul 13 '17 at 02:39

2 Answers2

3

You are sorting an array of strings, not integers, so that is the correct order. To make an array of Integers use @1, @2 etc. not @"1", @"2"

Actually @1, @2 creates NSNumber integer objects. NSArray can only store objects.

TheBasicMind
  • 3,585
  • 1
  • 18
  • 20
1

As @TheBasicMind said in his answer, you have an array of strings, not an array of integers. You are sorting your strings in character-by-character order, not numeric order.

Basic mind's solution of using an array of NSNumbers is probably the better solution, since it stores an array of numeric values rather than array of strings that represent numeric values.

Another solution would be to rewrite your sort code to use a string sort that uses the numeric value of your strings:

    NSArray *array = @[@"12", @"7", @"10", @"3", @"4", @"5",
                       @"6", @"1", @"8", @"9", @"2", @"11"];

    NSArray *sortedArray = [array sortedArrayUsingComparator: ^NSComparisonResult(
      NSString *string1,
      NSString *string2) {
        return [string1 compare: string2 options: NSNumericSearch];
    }];

    NSLog(@"Sorted array = %@", sortedArray);

That yields the following output:

Sorted array = (
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12
)
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • @vadian, why'd you delete your answer? I didn't realize/remember that `localizedStandardCompare` used numeric sorting rules. That's a good alternative to the other answers provided. – Duncan C Jul 13 '17 at 14:59