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

    }

原文地址:https://www.cnblogs.com/huangzs/p/4542603.html