Objective-C 选择排序

NSMutableArray *sourceArray = [NSMutableArray arrayWithObjects:@(3), @(5), @(7), @(9), @(2), @(4), @(8), @(6), nil];

    //选择排序

    for (int i = 0; i < sourceArray.count - 1; i++)

    {

        for (int j = i+1; j < sourceArray.count; j++)

        {

            NSInteger baseIdx = i;

            NSInteger moveIdx = j;

            

            NSNumber* baseNum = [sourceArray objectAtIndex:baseIdx];

            NSNumber* moveNum = [sourceArray objectAtIndex:moveIdx];

            if (baseNum.intValue > moveNum.intValue)

            {

                [sourceArray exchangeObjectAtIndex:baseIdx withObjectAtIndex:moveIdx];

            }

        }

    }

  //验证结果

    [sourceArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        NSLog(@"%d:%@", idx, obj);

    }];

posted on 2016-05-11 17:02  piaoliuping  阅读(97)  评论(0)    收藏  举报

导航