- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 冒泡法
NSMutableArray *arr = @[@"1",@"2344",@"4545",@"343335",@"1456",@"14",@"454",@"74",@"3945",@"1245"].mutableCopy;
NSInteger length = arr.count;
NSInteger repeatCount = 0;
NSInteger swappedCount = 0;
for (int i = 0, swapped = 1; swapped == 1 && i < length - 1; i ++) {
swapped = 0;
for (int j = 0; j < length - i - 1; j ++) {
repeatCount ++;
if ([arr[j] integerValue] > [arr[j + 1] integerValue]) {
NSString *tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = 1;
swappedCount ++;
}
}
}
NSLog(@"1循环次数 %ld",repeatCount);
NSLog(@"1交换次数 %ld", swappedCount);
NSMutableArray *arr2 = @[@"1",@"2344",@"4545",@"343335",@"1456",@"14",@"454",@"74",@"3945",@"1245"].mutableCopy;
// 选择法
repeatCount = 0;
swappedCount = 0;
for (int i = 0; i < length - 1; i ++) {
NSInteger index = i; // 核心 记录最小或者最大的坐标
for (int j = i + 1; j < length; j ++) {
repeatCount ++;
if ([arr2[index] integerValue] > [arr2[j] integerValue]) {
index = j;
}
}
if (index != i) {
swappedCount ++ ;
NSString *tmp = arr2[i];
arr2[i] = arr2[index];
arr2[index] = tmp;
}
}
NSLog(@"2循环次数 %ld",repeatCount);
NSLog(@"2交换次数 %ld", swappedCount);
}
网友评论