2 alllllllll alllllllll 于 2013.06.04 11:03 提问

对数组分类输出结果不正确

使用ios内置排序方法对数组进行分类,输出结果不对。后来用了冒泡排序法实现,想优化代码怎么解决?

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 )

1个回答

zhanglei5415
zhanglei5415   Rxr 2013.06.04 13:55
已采纳
numbers=[numbers sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     return [obj1 intValue] > [obj2 intValue];  //转成整型比较,才会拿到正确的排序结果
}];

NSLog(@"sorted array is %@",numbers);
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!