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]);

        }

  • 相关阅读:
    Oracle数据库的dual表的作用
    数据库中CASE函数和Oracle的DECODE函数的用法
    Oracle数据库中,通过function的方式建立自增字段
    Java学习(十三):抽象类和接口的区别,各自的优缺点
    Java学习(十八):二叉树的三种递归遍历
    Sublime工具插件安装
    sizeof和strlen
    I2C接口的EEPROM操作
    关于窗口看门狗
    关于指针传入函数
  • 原文地址:https://www.cnblogs.com/huangzs/p/4542603.html
Copyright © 2011-2022 走看看