快速排序

// 快速排序
- (void)fastSortWithArray:(NSMutableArray *)arr start:(NSInteger)start end:(NSInteger)end {
    if (start > end) return;
    NSInteger base,i,j;
    // 基准值可以随意位置取
    base = start;
    i = start;
    j = end;
    
    while (i != j) {
        while (i != j && [arr[j] intValue] >= [arr[base] intValue]) {
            j --;
        }
        while (i != j && [arr[i] intValue] <= [arr[base] intValue]) {
            i ++;
        }
       //  取大于base的索引与小于base位置互换
        [arr exchangeObjectAtIndex:i withObjectAtIndex:j];
    }
    // 更换基准值位置
    [arr exchangeObjectAtIndex:base withObjectAtIndex:i];

    [self fastSortWithArray:arr start:start end:i-1];
    [self fastSortWithArray:arr start:i+1 end:end];
}

start : 开始位置
end : 结束位置

你可能感兴趣的:(快速排序)