数组排序

1.冒泡法


    NSMutableArray *array=[NSMutableArray arrayWithArray:@[@"8",@"5", @"7", @"2", @"1"]];

    

     for (int i=0; i< array.count ; i++) {

        

        for (int j=0; j< array.count - 1 -i ; j++) {    /// -1 的目的交换次数为array.count - 1次, - i 获取要交换的数组

            if ([[array objectAtIndex:j] integerValue] > [[array objectAtIndex:j + 1] integerValue]) {  

                [array exchangeObjectAtIndex:j withObjectAtIndex:j+1];

            }

   

        }

   

    }


理解: 

首先第一轮通过使数组相邻的元素进行比较,第一轮会使元素中最大的值排到数组的最后面,而交换的次数为array.count - 1;

第二:因为第一轮已经将最大数移到了数组的最右边,所以只需将剩下的数组进行移位交换就可以了;

               除去排好的数组

1.5 7 2 1 8    array。count-1

2.5 2 1 7 8    array。count-2

3.2 1 5 7 8    array。count-3

4.1 2 5 7 8    array。count-4

(完成)

有上可得交换次数:array。count-1,  

所以:

 for (int i=0; i< array.count ; i++) {

        for (int j=0; j< array.count - 1 -i ; j++) {    /// -1 的目的交换次数为array.count - 1次, array.count - 1 -i 获取要交换的数组


有所思:其实在不用获取剩下的数组, 只要让数组循环次数达到 >= array。count-1让数组相邻元素比较,也可以获得排序成功后的数组;

 for (int i=0; i< array.count ; i++) {        //   关键 array.count   >= array.count-1;

        for (int j=0; j< array.count - 1  ; j++) {   



2.插入法







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值