排序数组不能正常工作?

时间:2013-06-03 12:35:35

标签: iphone sorting nsarray

I am sorting a array of string numbers using ios inbuilt sorting method but it is giving me wrong output.So I applied bubble sorting for a while,Any body can explaing why it is behaving like that.So that I can optimize my code.

NSArray *numbers=@[@"45",@"2",@"11",@"31",@"240",@"310"];
numbers=[numbers sortedArrayUsingSelector:@selector(compare:)];

NSLog(@"sorted array is %@",numbers);

NSMutableArray *m_Array=[[NSMutableArray alloc] initWithArray:numbers];

[numbers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    for (int j=idx+1; j<numbers.count; j++) {

        if ([m_Array[idx] intValue]>[m_Array[j] intValue]) {
            NSString *temp=m_Array[idx];
            [m_Array replaceObjectAtIndex:idx withObject:m_Array[j]];
            [m_Array replaceObjectAtIndex:j withObject:temp];
        }
    }
}];

NSLog(@"sorted array after bubble sort is %@",m_Array);

输出

排序数组是(     11,     2,     240,     31,     310,     45 )

冒泡排序后的

排序数组(     2,     11,     31,     45,     240,     310 )

3 个答案:

答案 0 :(得分:3)

那是因为你要比较字符串对象,而不是数字。

尝试将数组更改为数字而不是字符串(使用引号)。

换句话说,而不是

NSArray *numbers=@[@"45",@"2",@"11",@"31",@"240",@"310"];
你这样做:

NSArray *numbers=@{@45,@2,@11,@31,@240,@310};

(这是Objective-C文字,as described in this documentation),你会看到更好的结果。

“冒泡排序”方法更适合您的原因是因为您在该数组中获得了字符串对象的“intValue”。第一种算法没有发生这种情况。

答案 1 :(得分:1)

使用NSNumber而不是使用字符串将整数值添加到数组中。

 NSMutableArray *array =[NSMutableArray alloc]initWithObjects:[NSNumber      numberWithInteger:12],[[NSNumber numberWithInteger:122] ];

然后排序

[array sortedArrayUsingSelector:@selector(compare:)]

答案 2 :(得分:0)

这是因为Objective-C中的排序使用first元素对数据进行排序,如果第一个元素相同则查找下一个元素,否则它将根据第一个元素value.suppose 11和2的情况进行排序,如它检查第一个元素,2的第一个元素大于11的第一个元素(即; 1)。因此,它会将2声明为更大的排序目的。并且2将在11之后出现。

对于排序,您必须保留数字的前缀值才能正确排序。例如:3个数字的001,002,003和2个数字的01,02,03。

NSMutableArray *tempArray=[[NSMutableArray alloc] initWithCapacity:[numbers count]];
[numbers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [tempArray addObject:[NSString stringWithFormat:@"%03d",[numbers[idx] intValue]]];
}];

NSLog(@"sorted array is %@",[tempArray sortedArrayUsingSelector:@selector(compare:)]);

注意: ---仅适用于可变数字大小,---计算数组中的最大数量并以编程方式计数其数字并相应地设置字符串格式。

相关问题