冒泡排序的时间复杂度:O(n²)
实现方法一:
NSMutableArray *array = [NSMutableArray arrayWithArray:parameters];
for (int i = 0; i < parameters.count-1; i++) {
for (int j = 0; j < parameters.count-1-i; j++) {
if (array[j] > array[j+1]) {
[array exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
实现方法二:
NSMutableArray *array = [NSMutableArray arrayWithArray:parameters];
BOOL isExchange;
do {
isExchange = NO;
for (int i = 0; i < parameters.count - 1; i++) {
if ([parameters[i] compare:parameters[i+1]] == NSOrderedDescending) {
[parameters exchangeObjectAtIndex:i withObjectAtIndex:i+1];
isExchange = YES;
}
}
} while (isExchange);
方法二是优化之后的代码,如果某个数组只需交换一次便可完成排序,显然第二种方法加了标记更可取。
网友评论