OC版-快速排序,希尔排序

2021-09-26  本文已影响0人  木槿WEIXIAO

1.快速排序

//快速排序
- (void)quickSortWithArray:(NSMutableArray *)array
{
    [self quickSortWithArray:array begin:0 end:(int)array.count];
}
- (void)quickSortWithArray:(NSMutableArray *)array begin:(int)begin end:(int)end
{
    if (end - begin < 2) return;
    
    int mid = [self privotIndexWithBegin:begin end:end array:array];
    [self quickSortWithArray:array begin:begin end:mid];
    [self quickSortWithArray:array begin:mid + 1 end:end];
}
- (int)privotIndexWithBegin:(int)begin end:(int)end array:(NSMutableArray *)array
{
    NSNumber *privotV = array[begin];
    end--;
    
    BOOL right = YES;
    while (begin < end) {
        
        if (right) {
            //从右侧开始比较
            if ([privotV integerValue] < [array[end] integerValue]) {
                end--;
            }else{
                array[begin] = array[end];
                begin ++;
                right = NO;
            }
        }else{
            //从左侧开始比较
            if ([privotV integerValue] < [array[begin] integerValue]) {
                array[end] = array[begin];
                end --;
                right = YES;
            }else{
                begin ++;
            }
        }
    }
    
    array[begin] = privotV;
    return begin;
}

2.希尔排序

//希尔排序
- (void)shellSortWithArray:(NSMutableArray *)array
{
    NSMutableArray *stepArray = [self shellStepSquenceWithArray:array];
    for (int i = 0; i < stepArray.count; i ++) {
        int step = [stepArray[i] intValue];
        [self shellSortWithArray:array step:step];
    }
}
- (void)shellSortWithArray:(NSMutableArray *)array step:(int)step
{
    for (int col = 0; col < step; col ++) {
        
        //利用插入排序实现列排序(这里使用的是未优化的插入排序)
        for (int begin = col + step; begin < array.count; begin ++) {
            int current = begin;
            while (current > (step - 1)) {
                NSNumber *a = array[current];
                NSNumber *b = array[current - step];
                
                if ([a integerValue] < [b integerValue]) {
                    array[current] = b;
                    array[current - step] = a;
                    current = current - step;
                }else{
                    current = 0;
                }
            }
        }
        
        
    }
}
- (NSMutableArray *)shellStepSquenceWithArray:(NSMutableArray *)array
{
    NSMutableArray *stepArray = [[NSMutableArray alloc] init];
    int step = (int)array.count >> 1;
    while (step > 0) {
        step = step >> 1;
        [stepArray addObject:@(step)];
    }
    return stepArray;
}

上一篇 下一篇

猜你喜欢

热点阅读