[iOS基础]OC常用算法实现

  • 希尔排序
- (void)shellSort:(NSMutableArray *)array {
    
    NSInteger i,j,gap;
    NSInteger n = array.count;
    for (gap = n/2; gap > 0; gap/=2) {
        for (i=gap; i=0 && [array[j] integerValue] > [array[j +gap] integerValue]; j -= gap) {
                [array exchangeObjectAtIndex:j withObjectAtIndex:j+gap];
            }
        }
    }
}
  • 快速排序
- (void)qSort:(NSMutableArray *)array lowIndex:(NSInteger)low highIndex:(NSInteger)high{
    
    NSInteger pivot;
    while (low < high) {
        pivot = [self partition:array lowIndex:low highIndex:high];
        [self qSort:array lowIndex:low highIndex:pivot -1];
        low = pivot +1;
    }
    
}

- (NSInteger)partition:(NSMutableArray *)array lowIndex:(NSInteger)low highIndex:(NSInteger)high{
    NSInteger pivotKey;
    pivotKey = [array[low] integerValue];
    while (low < high) {
        while (low < high && [array[high] integerValue] >= pivotKey) {
            high -- ;
        }
        array[low] = array[high];
        while (low < high && [array[low] integerValue] <= pivotKey) {
            low ++ ;
        }
        array[high] = array[low];
        
    }
    array[low] = @(pivotKey);
    return low;
}

  • 直接插入排序
- (void)insertSort:(NSMutableArray *)array{
    NSInteger i,j,temp;
    NSInteger n = array.count;
    for (i = 1; i=0&&[array[j] integerValue] > temp; j--) {
                array[j +1] = array[j];
            }
            array[j+1] = @(temp);
        }
    }
}
  • 简单选择排序
- (void)selectedSort:(NSMutableArray *)array{
    
    NSInteger i,j,min;
    NSInteger n = array.count;
    for (i=0; i
  • 冒泡排序
- (void)bubbleSort:(NSMutableArray *)array{
    NSInteger i,j;
    NSInteger n = array.count;
    BOOL flag = YES;
    for (i = 0; ii; j--) {
            if ([array[j] integerValue] < [array[j-1] integerValue]) {
                [array exchangeObjectAtIndex:j withObjectAtIndex:j-1];
                flag = YES;
            }
        }
    }
}

你可能感兴趣的:([iOS基础]OC常用算法实现)