# iOS冒泡排序

2018-02-07 10:35:28来源:oschina作者:zh_iOS人点击

- (void)bubbleSort:(NSMutableArray *)arr {
int count = 0;
int cycleCount = 0;
for (int i = 0; i cycleCount += 1;
// 每次循环都不需要比较最后一个，倒数第二个，倒数第三个... 所以二层循环最好减去已经排好序的数
for (int j = 0; j cycleCount += 1;
if ([arr[j] integerValue] > [arr[j+1] integerValue]) {
NSInteger temp = [arr[j] integerValue];
arr[j] = arr[j+1];
arr[j+1] = @(temp);
count += 1;
}
}
}
NSLog(@"交换次数-->%@",@(count));
NSLog(@"循环次数-->%@",@(cycleCount));
NSLog(@"%@",arr);
}

- (void)bubbleSort:(NSMutableArray *)arr {
int count = 0;
int cycleCount = 0;
for (int i = 0; i cycleCount += 1;
finished = YES;
for (int j = 0; j cycleCount += 1;
if ([arr[j] integerValue] > [arr[j+1] integerValue]) {
NSInteger temp = [arr[j] integerValue];
arr[j] = arr[j+1];
arr[j+1] = @(temp);
finished = NO;
count += 1;
}
}
if (finished) break;
}
NSLog(@"----交换次数为%@",@(count));
NSLog(@"----循环次数为%@",@(cycleCount));
NSLog(@"%@",arr);
}

- (void)bubbleSort3:(NSMutableArray *)arr {
int count = 0;
int cycleCount = 0;
int pos = (int)arr.count-1;
for (int i = 0; i finished = YES;
cycleCount += 1;
int currentPos = 0;
// 从上一次发生交换的位置开始循环
for (int j = 0; j cycleCount += 1;
if ([arr[j] integerValue] > [arr[j+1] integerValue]) {
NSInteger temp = [arr[j] integerValue];
arr[j] = arr[j+1];
arr[j+1] = @(temp);
count += 1;
// 记录发生交换的位置
currentPos = j;
finished = NO;
}
}
pos = currentPos;
if (finished) break;
}
NSLog(@"交换次数-->%@",@(count));
NSLog(@"循环次数-->%@",@(cycleCount));
NSLog(@"%@",arr);
}