1.冒泡法
NSMutableArray *array=[NSMutableArray arrayWithArray:@[@"8",@"5", @"7", @"2", @"1"]];
for (int i=0; i< array.count ; i++) {
for (int j=0; j< array.count - 1 -i ; j++) { /// -1 的目的交换次数为array.count - 1次, - i 获取要交换的数组
if ([[array objectAtIndex:j] integerValue] > [[array objectAtIndex:j + 1] integerValue]) {
[array exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
理解:
首先第一轮通过使数组相邻的元素进行比较,第一轮会使元素中最大的值排到数组的最后面,而交换的次数为array.count - 1;
第二:因为第一轮已经将最大数移到了数组的最右边,所以只需将剩下的数组进行移位交换就可以了;
除去排好的数组
1.5 7 2 1 8 array。count-1
2.5 2 1 7 8 array。count-2
3.2 1 5 7 8 array。count-3
4.1 2 5 7 8 array。count-4
(完成)
有上可得交换次数:array。count-1,
所以:
for (int i=0; i< array.count ; i++) {
for (int j=0; j< array.count - 1 -i ; j++) { /// -1 的目的交换次数为array.count - 1次, array.count - 1 -i 获取要交换的数组
有所思:其实在不用获取剩下的数组, 只要让数组循环次数达到 >= array。count-1让数组相邻元素比较,也可以获得排序成功后的数组;
for (int i=0; i< array.count ; i++) { // 关键 array.count >= array.count-1;
for (int j=0; j< array.count - 1 ; j++) {