算法 -- 排序

Posted 风痕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法 -- 排序相关的知识,希望对你有一定的参考价值。

冒泡排序:

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

 

 NSArray * testArray = @[@12,@188,@26,@24,@17,@88];
    NSMutableArray * nA = [NSMutableArray arrayWithArray: testArray];

    
    for (NSInteger i = 0; i < nA.count; i++) { //外层循环次数
        for (NSInteger j = 0; j < nA.count - 1 - i; j++) { //内层循环次数,(外层没循环1次则会在数组最后1个位置获取到1个最大值,所有此处循环次数为 (总次数 - 1 - i) 次)
            NSInteger temp = [nA[j + 1] integerValue];
            NSLog(@"%d",temp);
            if ([nA[j] integerValue] > [nA[j + 1] integerValue]) { //如果前面一个大于后面一个,则交换位置
                nA[j + 1]  = nA[j];
                nA[j] = [NSNumber numberWithInt: temp];
            }
            
              NSLog(@"%@",nA);
        }
    }
    
    NSLog(@"%@",nA);

 

以上是关于算法 -- 排序的主要内容,如果未能解决你的问题,请参考以下文章

算法排序之堆排序

快速排序-递归实现

从搜索文档中查找最小片段的算法?

在第6731次释放指针后双重免费或损坏

TimSort算法分析

以下代码片段的算法复杂度