OC冒泡排序

    NSMutableArray *p = [[NSMutableArray alloc] initWithObjects:@"3",@"5",@"4",@"1",@"7",@"6",@"4",nil];
    for (int i = 0; i<[p count]; i++)
    {
        for (int j=i+1; j<[p count]; j++)
        {
            int a = [[p objectAtIndex:i] intValue];
            int b = [[p objectAtIndex:j] intValue];
            if (a > b)
            {
                [p replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%d",b]];
                [p replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%d",a]];
            }
        }
    }
    for (int i = 0; i<[p count]; i++)
    {
        NSLog(@"%@",[p objectAtIndex:i]);
    }

时间

平均复杂度:O(n^2)

最坏复杂度:O(n^2)

最好复杂度: O(n)

空间

复杂度: O(1) 稳定

 

另一种实现方式

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"3",@"5",@"4",@"1",@"7",@"6",@"8",nil];

    //外循环控制排序趟数,进行array.count-1趟

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

        //内循环为每趟比较的次数,第i趟比较array.count-i次

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

            NSString *m=array[j];

            NSString *n=array[j+1];

            if (m.integerValue > n.integerValue) {

                [array exchangeObjectAtIndex:j+1 withObjectAtIndex:j];

            }

        }

    }

    for (int i = 0; i<[array count]; i++)

    {

        NSLog(@"%@",[array objectAtIndex:i]);

    }

posted @   黄增松  阅读(439)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示