IOS常见算法

2018-08-14  本文已影响16人  西门淋雨

常见算法:

快速排序:
//快速排序
- (void)quckSort:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right{
    if (left >= right) {
        return;
    }
    NSInteger leftIndex = left;
    NSInteger rightIndex = right;
    NSInteger key = [arr[leftIndex] integerValue];
    
    while (leftIndex < rightIndex) {
        //首先从右边开始找比key小的值
        while (leftIndex < rightIndex && [arr[rightIndex] integerValue] >= key) {//比key大则继续寻找
            rightIndex --;
        }
        //找到后,替换key的位置
        arr[leftIndex] = arr[rightIndex];
        //从左到右找比key大的值
        while (leftIndex < rightIndex && [arr[leftIndex] integerValue] < key) {
            leftIndex ++;
        }
        //找到后替换位置
        arr[rightIndex] = arr[leftIndex];
    }
    //退出循环代表left = right
    arr[leftIndex] = @(key);
    //递归左边
    [self quckSort:arr leftIndex:left rightIndex:leftIndex-1];
    //递归右边
    [self quckSort:arr leftIndex:leftIndex + 1 rightIndex:right];
}
选择排序:
-(void)selctSort:(NSMutableArray *)array{
    for (NSInteger i = 0; i < array.count; i++) {
        for (NSInteger j = i+1; j<array.count; j++) {
            if ([array[j] integerValue] < [array[i] integerValue]) {
                NSInteger temp = [array[i] integerValue];
                array[i] = @([array[j] integerValue]);
                array[j] = @(temp);
            }
        }
    }
}
冒泡排序:
-(void)maopaoSort:(NSMutableArray *)array{
    for (NSInteger i = 0; i < array.count; i++) {
        for (NSInteger j = 0; j<array.count-i-1; j++) {
            if ([array[j] integerValue] < [array[j+1] integerValue]) {
                NSInteger temp = [array[j] integerValue];
                array[j] = @([array[j+1] integerValue]);
                array[j+1] = @(temp);
            }
        }
    }
}
测试代码:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //快速排序
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@(55), @(23),@(93),@(23),@(4),@(56),@(1),@(34),@(69), nil];
    [self quckSort:arr leftIndex:0 rightIndex:arr.count-1];
     NSLog(@"%@",arr);
    NSMutableArray *arr2 = [NSMutableArray arrayWithObjects:@(55), @(23),@(93),@(23),@(4),@(56),@(1),@(34),@(69), nil];
    //选择排序
    [self selctSort:arr2];
    NSLog(@"%@",arr2);
    //冒泡-重复的走访要排序的数列,一次两个,顺序不对则交换顺序,
    NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:@(55), @(23),@(93),@(23),@(4),@(56),@(1),@(34),@(69), nil];
    [self maopaoSort:arr3];
    NSLog(@"%@",arr3);
}
上一篇下一篇

猜你喜欢

热点阅读