原理:
数组中每一个数同其他数做比较,大的数放在数组对尾部,小的数放在数组前部
- 上代码
// 创建数组
NSMutableArray *arr = [NSMutableArray array];
for (int i = 0; i < 20; i++) {
int a = arc4random()%(100+10);
[arr addObject:@(a)];
}
NSLog(@"初始值:%@",arr);
2017-03-08 11:20:36.923 冒泡排序[2827:81020] 初始值:(
108,1,46,36,53,8,97,8,34,18,85,88,11,54,31,104,29,21,35,1)
// 排序核心方法
+(NSMutableArray *)getSortArrayWithArray:(NSMutableArray *)array {
for (int i = 0; i < array.count; i++) {
// 每个数和剩余的其他数作比较
for (int j = 0; j < array.count-1-i; j++) {
if ([array objectAtIndex:j] > [array objectAtIndex:j+1]) {
id tempA = [array objectAtIndex:j];
id tempB = [array objectAtIndex:j+1];
[array replaceObjectAtIndex:j+1 withObject:tempA];
[array replaceObjectAtIndex:j withObject:tempB];
}
}
}
return array;
}
// 开始排序
NSMutableArray *newArr = [SortArray getSortArrayWithArray:arr];
NSLog(@"排序后:%@",newArr);
2017-03-08 11:20:36.925 冒泡排序[2827:81020] 排序后:(
1,
1,
8,
8,
11,
18,
21,
29,
31,
34,
35,
36,
46,
53,
54,
85,
88,
97,
104,
108
)