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 )