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

        }

  • 相关阅读:
    Codeforces Round #213 (Div. 2) B. The Fibonacci Segment
    关于求解不定方程的n(n-1)=2m(m-1)的解法的总结
    objective-c @()
    objective-c 条件运算符
    关于判断两个矩阵相交的一点想法
    二维几何常用运算
    《为ipad而设计 打造畅销APP》读书笔记
    ios cocos2d FPS过低的解决方法
    python 根据对象和方法名,返回提供这个方法的定义的类
    python 获取类的属性
  • 原文地址:https://www.cnblogs.com/huangzs/p/4542603.html
Copyright © 2011-2022 走看看