oc 算法:冒泡排序/快速排序/选择排序

本文介绍了三种常见的排序算法:冒泡排序、快速排序和选择排序,并提供了详细的Objective-C代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近温习了下算法,顺便把代码记录下来

冒泡排序

- (void)sortByBubble {
    NSMutableArray *array = [NSMutableArray arrayWithArray:@[@2, @1, @4, @8, @7, @3, @9]];

    for (int i = 0; i < array.count; i++) {
        for (int j = 0; j < array.count -1; j ++) {
            if ([array[j] integerValue] > [array[j+1] integerValue]) {
                [array exchangeObjectAtIndex:j+1 withObjectAtIndex:j];
            }
        }
    }
}

快速排序

- (void)fastSortWithLeftIndex:(NSInteger)leftIndex rightIndex:(NSInteger)rightIndex arrar:(NSMutableArray *)array {
    if (leftIndex >= rightIndex)  {
        return;
    }
    //右边找小的    左边找大的
    NSInteger base = [array[leftIndex] integerValue];
    NSInteger i = leftIndex;
    NSInteger j = rightIndex;

    while (i != j) {
        //从右边开始找比基准模型的评分小的模型
        while (i < j && base <= [array[j] integerValue] ) {
            j--;
        }
        //从左向右找 找到小的就继续while循环  找到大的就记录 i
        while (i < j &&  base >= [array[i] integerValue] ) {
            i ++;
        }
        LYLog(@"%@",array);
        //如果左右都找到了就交换模型
        if (i < j) {
            [array exchangeObjectAtIndex:i withObjectAtIndex:j];
        }
    }
    LYLog(@"_________________");
    //相遇了  基准数字 归位
    [array exchangeObjectAtIndex:i withObjectAtIndex:leftIndex];
    LYLog(@"%@",array);
    [self fastSortWithLeftIndex:leftIndex rightIndex:i-1 arrar:array];
    [self fastSortWithLeftIndex:i+1 rightIndex:rightIndex arrar:array];

}

选择排序

- (void)sortBySelectArray {
    NSMutableArray *array = [NSMutableArray arrayWithArray:@[@2, @1, @4, @8, @7, @3, @9]];
    for (int i = 0; i < array.count - 1; i ++) {

        for (int j = i + 1; j < array.count; j ++) {

            if ([array[i] integerValue] > [array[j] integerValue]) {
                [array exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
            LYLog(@"%@",array);

        }
        LYLog(@"_____________________");
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值