iOS算法:用OC实现一个快速排序

用OC实现一个快速排序

算法实现:

- (NSArray *)quickSortWithArray:(NSArray *)array {
    if (!array) {
        return @[];
    }
    if (array.count == 0 || array.count == 1) {
        return array;
    }
    NSMutableArray *sortedArray = [NSMutableArray array];
    NSInteger baseNumberIndex = random() % array.count;
    NSNumber *baseNumber = array[baseNumberIndex];
    NSMutableArray *unsortedArray = [array mutableCopy];
    [unsortedArray removeObjectAtIndex:baseNumberIndex];
    NSMutableArray *leftArray = [NSMutableArray array];
    NSMutableArray *rightArray = [NSMutableArray array];
    
    for (NSNumber *curNumber in unsortedArray) {
        if (curNumber.integerValue < baseNumber.integerValue) {
            [leftArray addObject:curNumber];
        } else {
            [rightArray addObject:curNumber];
        }
    }
    
    [sortedArray addObjectsFromArray:[self quickSortWithArray:[leftArray copy]]];
    [sortedArray addObject:baseNumber];
    [sortedArray addObjectsFromArray:[self quickSortWithArray:[rightArray copy]]];
    
    return sortedArray;
}

测试函数:

- (void)handleSubject {
    
    /**INPUT*/
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < 10000; i++) {
        NSInteger num = random() % 10000 - 5000;
        [array addObject:@(num)];
    }
//    NSLog(@"pre sort | %@",array);
    
    /**SORTING*/
    [self startTimeConsuming];
    NSArray *sortedArray = [self quickSortWithArray:array];
    [self endTimeConsuming];
    
    /**OUTPUT*/
//    NSLog(@"after sort | %@",sortedArray);
}

输出耗时:

2019-01-09 09:52:20.919685+0800 CLLeetcode[16387:801648] the time consuming is 28.318115 ms

你可能感兴趣的:(iOS算法:用OC实现一个快速排序)