冒泡排序优化
2017-10-23 09:45
176 查看
之前使用冒泡排序只是暂时的进行相邻的数据进行交换,这样效率不是很高。现在进行对之前的冒泡排序进行优化。
这样循环次数和打印次数明显比之前的少了很多。
// 冒泡排序 - (void)functionNice { int count = 0; // 比较多少次 int forcount = 0; // 循环多少次 BOOL flag = YES; NSMutableArray *arr = @[@16, @1, @2, @9, @7, @12, @5, @3, @8, @13, @10].mutableCopy; for (int i = 0; i < arr.count && flag; i++) { forcount ++; flag = NO; for (int j = (int)arr.count - 2; j > i; j --) { count ++; if (arr[j] < arr[j + 1]) { [arr exchangeObjectAtIndex:j withObjectAtIndex:j + 1]; flag = YES; } } [self logArr:arr]; } NSLog(@"循环次数 %d", forcount); NSLog(@"共 %d 次比较", count); } - (void)logArr:(NSMutableArray *)array { NSString *str = @""; for (NSNumber *number in array) { str = [str stringByAppendingString:[NSString stringWithFormat:@"%zd", [number integerValue]]]; } NSLog(@"%@", str); }
这样循环次数和打印次数明显比之前的少了很多。