插入排序

1.原理:从原数组中依次取出数据,按照大小找到新数组的位置,然后插入进去
2.代码实现

/**
 * 插入排序
 */
public class InsertSort {

    public static void main(String[] args) {
        int[] array = new int[]{6546,54654,4654654,4544,2132,224,2432,44,4525,465465,46,6446,44646};
        int[] temp = insertSort(array);
        for(int a : temp){
            System.out.println(a);
        }
    }


    private static int[] insertSort(int[] arr){
        int[] temp = null;
        for(int a : arr){
            //当temp为空时,初始化temp
            if(temp == null){
                temp = new int[]{a};
                continue;
            }
            //如果a大于temp的最大值,直接扩容temp,然后将a放在temp最后的位置,继续循环
            if(a >= temp[temp.length-1]){
                temp = Arrays.copyOf(temp, temp.length+1);
                System.arraycopy(temp,0,temp,0,temp.length);
                temp[temp.length-1] = a;
                continue;
            }
            //如果a小于temp最小值,直接扩容temp,将temp数据全部后移一位,然后把a放在第一位,继续循环
            if(a < temp[0]){
                temp = Arrays.copyOf(temp, temp.length+1);
                System.arraycopy(temp,0,temp,1,temp.length-1);
                temp[0] = a;
                continue;
            }
            
            for(int i = 0; i< temp.length-1; i++){
                //扩容,然后将i之后的数据全部后移一位,将a放入i+1的位置
                if (a >= temp[i] && a < temp[i+1]) {
                    temp = Arrays.copyOf(temp, temp.length+1);
                    System.arraycopy(temp,i+1,temp,i+2,temp.length-i-2);
                    temp[i+1] = a;
                    break;
                }
            }
        }
        return temp;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值