zoukankan      html  css  js  c++  java
  • 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]);

        }

  • 相关阅读:
    How to install php 7.x on CentOS 7
    Azure新建的CentOS设置root账户的密码
    远程激活.NET REFLECTOR(不能断网)
    C# WebApi 配置复杂路由不生效的问题
    在Mac上激活Adobe产品
    WIN10更新后出现无法联网的问题
    Mac安装SSHFS挂载远程服务器上的文件夹到本地
    输入三个数值,输出其中的最大值和最小值
    登录接口,只为自己能尽快吐槽一下这段代码
    随手记
  • 原文地址:https://www.cnblogs.com/huangzs/p/4542603.html
Copyright © 2011-2022 走看看