做面试题遇到用obj-c写冒泡排序,随便写了个
- (NSMutableArray *)sorted:(NSMutableArray *)array
{
int len = [array count];
for (int j = 0 ; j < len-1; j++) {
for (int i = 0; i < len-1-j; i++) {
if ([[array objectAtIndex:i] compare:[array objectAtIndex:i+1]] > 0) {
NSObject *temp = [array objectAtIndex:i];
[array replaceObjectAtIndex:i withObject:[array objectAtIndex:i+1]];
[array replaceObjectAtIndex:i+1 withObject:temp];
}
}
}
return array;
}
这是从小到大,从大到小的话直接这样调
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"3",@"5",@"1",@"2", nil];
NSMutableArray *sortedArr = [self sorted:arr];
NSArray *reverseArr = [[sortedArr reverseObjectEnumerator] allObjects];
NSLog(@"%@",reverseArr);