OC快速排序

OC快速排序

好久没有回顾学过的东西了,今天要用到快排的时候居然忘记了,好记性不如烂笔头啊,回顾下快速排序

快速排序的思想简单明了,核心精髓在于分割

1:选基数,假设每次都取最左边的为基数,并假设该基数是最小的(最终结果也是升序,倒序也可以效仿)

2:划分,扫描所要排序的区间;小于基数的放到左侧,并且交换

3:分别对左侧和右侧重复第二部的操作

代码如下

//分割位置

-(NSInteger)partion:(NSMutableArray*)source lowPosition:(NSInteger)lowIndex HighPosition:(NSInteger)hightIndex

{

    if (lowIndex==hightIndex) {

        return lowIndex;

    }

    //假设取最左边为比较对象

    NSNumber *base = source[lowIndex];

    

    NSInteger i = lowIndex;//比较对象在数组中的索引位置

    for (NSInteger j=lowIndex; j<=hightIndex; j++) {

        if ([source[j]integerValue]<base.integerValue)//找到一个比比较对象小的位置就右移一位,同时交换改两个位置上的数

        {

            i++;

            

            NSNumber *temp = source[i];

            source[i] = source[j];

            source[j] = temp;

        }

    }

    //扫描完毕后把比较对象放在对应位置

    NSNumber *temp2 = source[i];

    source[i] = base;

    source[lowIndex] = temp2;

    

    

    return i;

}

-(void)quickSort:(NSMutableArray*)source startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex

{

    if (startIndex<endIndex) {

        NSInteger partPosition = [selfpartion:sourcelowPosition:startIndexHighPosition:endIndex];

        [selfquickSort:sourcestartIndex:startIndexendIndex:partPosition-1];

        [selfquickSort:sourcestartIndex:partPosition+1endIndex:endIndex];

    }

}

//检查验证

-(void)test

{

NSMutableArray *arr = [[NSMutableArrayalloc]init];

    for (int i=0; i<100; i++) {

        int random = arc4random();

        [arr addObject:@(random)];

    }

    [selfquickSort:arrstartIndex:0endIndex:arr.count-1];

for (NSNumber *itemin arr) {

        NSLog(@"%@",item);

    }

}

打印结果验证



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值