1、冒泡排序
- (void)sortBubbleArray {
NSArray *numArr = @[@(10), @(1), @(7), @(2), @(8)];
NSMutableArray *oldArr = [NSMutableArray arrayWithArray:numArr];
for (NSInteger x = 0; x < oldArr.count; x++) {
for (NSInteger y = 0; y < oldArr.count - x - 1; y++) {
if ([oldArr[y + 1] integerValue] < [oldArr[y] integerValue]) {
NSInteger temp = [oldArr[y + 1] integerValue];
oldArr[y + 1] = oldArr[y];
oldArr[y] = @(temp);
}
}
}
NSLog(@"冒泡排序结果:%@", oldArr);
}2、选择排序
- (void)sortSelectedArray {
NSArray *numArr = @[@(10), @(1), @(7), @(2), @(8)];
NSMutableArray *oldArr = [NSMutableArray arrayWithArray:numArr];
for (NSInteger x = 0; x < oldArr.count; x++) {
for (NSInteger y = x + 1; y < oldArr.count; y++) {
if ([oldArr[y] integerValue] < [oldArr[x] integerValue]) {
NSInteger temp = [oldArr[y] integerValue];
oldArr[y] = oldArr[x];
oldArr[x] = @(temp);
}
}
}
NSLog(@"选择排序结果:%@", oldArr);
}
本文详细介绍了冒泡排序和选择排序算法的实现过程,并通过示例代码进行了对比演示。

3万+

被折叠的 条评论
为什么被折叠?



