How to sort an Array of signed numbers in iOS?

*爱你&永不变心* 提交于 2019-12-11 20:21:42

问题


This may be a simple question, but i don't know the way of doing sorting of array of signed integer values.

My array before sorting,

pointsAry (-2,-7,-5,0,-3,2,-1,-4,1,3,-6)

After using

NSArray * sortedArray = [pointsAry sortedArrayUsingComparator:^(id str1, id str2){
        return [(NSString *)str1 compare:(NSString *)str2 options:NSNumericSearch];
    }];

Result

sortedArray : (-1,-2,-3,-4,-5,-6,-7,0,1,2,3)

for signed values the sortedArray format is not correct, so i need like

(-7,-6,-5,-4,-3,-2,-1,0,1,2,3)

How to sort like above format ? Thanks in advance.


回答1:


NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
    return [@([str1 intValue]) compare:@([str2 intValue])];
}];



回答2:


The following comparator avoids the creation of temporary NSNumber objects:

NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return my_int_compare([str1 intValue], [str2 intValue]);
}];

where

static inline int my_int_compare(int x, int y) { return (x > y) - (x < y); }

is a helper function that compares two integers and returns -1, 0, or +1 (as required for a comparator method), using the technique from

  • Is there a standard sign function (signum, sgn) in C/C++?.

Of course the problem only arises because the array contains NSString objects. Using NSNumbers would be the better solution.

Using the NSNumericSearch option does not help because it does not treat the minus sign as part of the number.




回答3:


NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];
    NSMutableArray *num=[[NSMutableArray alloc]init];
    for(int i=0;i<array.count;i++)
    {
        NSString *str=array[i];
       [num addObject: [str substringFromIndex:1]];
    }



    NSArray *sortedArray = [num sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
        return [@([str1 intValue]) compare:@([str2 intValue])];
    }];
    [array removeAllObjects];
    for(int i=0;i<sortedArray.count;i++)
    {
        NSString *newString = [NSString stringWithFormat:@"P%@",sortedArray[i]];


        [array addObject:newString];
    }

It's work for me



来源:https://stackoverflow.com/questions/20212998/how-to-sort-an-array-of-signed-numbers-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!