使用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 )
numbers=[numbers sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 intValue] > [obj2 intValue]; //轉成整型比較,才會拿到正確的排序結果
}];
NSLog(@"sorted array is %@",numbers);