最近温习了下算法,顺便把代码记录下来
冒泡排序
- (void)sortByBubble {
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@2, @1, @4, @8, @7, @3, @9]];
for (int i = 0; i < array.count; i++) {
for (int j = 0; j < array.count -1; j ++) {
if ([array[j] integerValue] > [array[j+1] integerValue]) {
[array exchangeObjectAtIndex:j+1 withObjectAtIndex:j];
}
}
}
}
快速排序
- (void)fastSortWithLeftIndex:(NSInteger)leftIndex rightIndex:(NSInteger)rightIndex arrar:(NSMutableArray *)array {
if (leftIndex >= rightIndex) {
return;
}
//右边找小的 左边找大的
NSInteger base = [array[leftIndex] integerValue];
NSInteger i = leftIndex;
NSInteger j = rightIndex;
while (i != j) {
//从右边开始找比基准模型的评分小的模型
while (i < j && base <= [array[j] integerValue] ) {
j--;
}
//从左向右找 找到小的就继续while循环 找到大的就记录 i
while (i < j && base >= [array[i] integerValue] ) {
i ++;
}
LYLog(@"%@",array);
//如果左右都找到了就交换模型
if (i < j) {
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
LYLog(@"_________________");
//相遇了 基准数字 归位
[array exchangeObjectAtIndex:i withObjectAtIndex:leftIndex];
LYLog(@"%@",array);
[self fastSortWithLeftIndex:leftIndex rightIndex:i-1 arrar:array];
[self fastSortWithLeftIndex:i+1 rightIndex:rightIndex arrar:array];
}
选择排序
- (void)sortBySelectArray {
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@2, @1, @4, @8, @7, @3, @9]];
for (int i = 0; i < array.count - 1; i ++) {
for (int j = i + 1; j < array.count; j ++) {
if ([array[i] integerValue] > [array[j] integerValue]) {
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
LYLog(@"%@",array);
}
LYLog(@"_____________________");
}
}