OC常用算法

排序算法

冒泡排序

- (void)bubbleSort:(NSMutableArray *)ary {
    NSLog(@"\n排序前\n");
    [self printAry:ary];
    
    for (int i = 0 ; i < ary.count ; i ++) {
        for (int j = 0; j < ary.count - i - 1; j ++) {
            if ([ary[j] intValue] > [ary[j + 1] intValue]) {
                [ary exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
            }
        }
    }
    
    NSLog(@"\n排序后\n");
    [self printAry:ary];
}
- (void)bubbleSort:(NSMutableArray *)ary {
    NSLog(@"\n排序前\n");
    [self printAry:ary];
    for (int i = 0; i < ary.count ; i++) {
        for (int j = ary.count - 2; j >= i; j--) {
            if ([ary[j] intValue] > [ary[j + 1] intValue]) {
                [ary exchangeObjectAtIndex:j  withObjectAtIndex:j + 1];
                [self printAry:ary];
            }
        }
    }
    
    NSLog(@"\n\n\n\n排序后\n");
    [self printAry:ary];
}

选择排序

- (void)selectSort:(NSMutableArray *)ary {
    NSInteger idx;
    for (NSInteger i = 0 ; i < ary.count - 1; i++) {
        idx = i;
        for (NSInteger j = i + 1; j < ary.count ; j++) {
            if (ary[idx].intValue > ary[j].intValue) {
                idx = j;
            }
        }
        if (idx != i) {
            [ary exchangeObjectAtIndex:i withObjectAtIndex:idx];
        }
    }
}

快速排序

- (void)quickSort:(NSMutableArray *)ary
          leftIdx:(NSInteger)leftIdx
         rightIdx:(NSInteger)rightIdx {
    if (leftIdx >= rightIdx) {
        return;
    }
    NSInteger i = leftIdx;
    NSInteger j = rightIdx;
    
    NSInteger key = ary[i].intValue;
    
    while (i < j)  {
        while (i < j && ary[j].intValue >= key) {
            j--;
        }
        ary[i] = ary[j];
        
        while (i < j && ary[i].intValue <= key) {
            i++;
        }
        ary[j] = ary[i];
    }
    
    ary[i] = @(key);
    [self quickSort:ary leftIdx:leftIdx rightIdx:i-1];
    [self quickSort:ary leftIdx:i+1 rightIdx:rightIdx];
}

插入

- (void)straightInsertionSortWithNumbers:(NSMutableArray *)numbers {
    for (int i = 1; i < numbers.count; i++) {
        if ([numbers[i - 1] intValue] > [numbers[i] intValue]) {//前面一位大于后面一位
            int temp = [numbers[i] intValue];
            for (int j = i - 1; j >= 0 && [numbers[j] intValue] > temp; j--) {
                [numbers exchangeObjectAtIndex:j + 1 withObjectAtIndex:j];
            }
        }
    }
    NSLog(@"%@",numbers);
}

二分查找

- (NSInteger)halfSearch:(NSMutableArray *)ary
            target:(NSNumber *)target {
    NSInteger low = 0;
    NSInteger high = ary.count - 1;
    while (low <= high) {
        NSInteger mid = (low + high) / 2;
        if (ary[mid].intValue < target.intValue) {
            low = mid + 1;
        } else if (ary[mid].intValue > target.intValue) {
            high = mid - 1;
        } else {
            return mid;
        }
    }
    return -1;
}

你可能感兴趣的:(OC常用算法)