冒泡排序?qū)崿F(xiàn)的基本方案:兩個(gè)循環(huán)。
在基本方案上做優(yōu)化:
方案1伊脓、在基本方案的基礎(chǔ)上府寒,增加子循環(huán)無(wú)交換時(shí),排序結(jié)束的邏輯报腔;
方案2株搔、在方案1的基礎(chǔ)上,增加子循環(huán)中最小值交換到首位的邏輯纯蛾;
方案3纤房、在基本方案的基礎(chǔ)上,增加子循環(huán)中最小值交換到首位的邏輯翻诉,增加遍歷到上次子循環(huán)最后一次交換時(shí)的位置的邏輯炮姨;
優(yōu)化方案3的實(shí)現(xiàn)代碼如下:
// 方案3、在基本方案的基礎(chǔ)上碰煌,增加子循環(huán)中最小值交換到首位的邏輯舒岸,增加遍歷到上次子循環(huán)最后一次交換時(shí)的位置的邏輯;
- (void)bubbleSortExchangeMinEndToMax
{
NSMutableArray *list = [NSMutableArray arrayWithArray:@[@1,@3,@2,@8,@5]];
NSInteger sum = 0;
NSInteger maxj = list.count - 1;
for (int i = 0; i < list.count; i ++) {
NSInteger min = [list[i] integerValue];;
NSInteger minIndex = i;
NSInteger lastExchangeIndex = i;
for (int j = i; j < maxj; j ++) {
NSInteger left = [list[j] integerValue];
NSInteger right = [list[j + 1] integerValue];
if (left > right) {
[list exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
lastExchangeIndex = j;
if (MIN(left, right) < min) {
min = MIN(left, right);
minIndex = j;
}
}
sum ++;
}
maxj = lastExchangeIndex;
if (minIndex != i) {
[list exchangeObjectAtIndex:minIndex withObjectAtIndex:i];
}
}
NSLog(@"endmax sum :%ld sort: %@", sum, list);
}
在方案2或者方案3的基礎(chǔ)(增加子循環(huán)中最小值交換到首位的邏輯)上提出一個(gè)問(wèn)題:
記錄子循環(huán)的交換次數(shù)exchangeCount:若exchangeCount<3拄查,最小值交換到首位后吁津,排序是否結(jié)束棚蓄?請(qǐng)證明堕扶。