归并排序

 public static void execute(int[] arr){

        // 当数组的长度小于等于1时就停止拆分
        if(arr.length > 1){

            /*左递归*/
            int len = arr.length;
            int leftLen = len/2;
            int[] leftArr = new int[leftLen];
            System.arraycopy(arr,0,leftArr,0,leftLen);
            execute(leftArr);

            /*右递归*/
            int rigthLen = len - leftLen;
            int[] rigthArr = new int[rigthLen];
            System.arraycopy(arr,leftLen,rigthArr,0,rigthLen);
            execute(rigthArr);

            /*这里我们需要用个临时数组来存放排序后的数组,然后把临时数组的值copy到上一栈帧的局部变量表存放*/
            int[] temp = merge(leftArr,rigthArr);
            System.arraycopy(temp,0,arr,0,len);
        }
    }
    /**
     * @deprecated 合并
     * @param left 左边的数组
     * @param right 右边的数组
     * @return arr
     */
    public static int[] merge(int[] left,int[] right){
        int leftLen = left.length;
        int rightLen = right.length;
        int[] arr = new int[leftLen+rightLen];
        int i = 0,j = 0,index = 0;

        while (i < leftLen && j < rightLen){
            if(left[i] > right[j]){
                arr[index++] = right[j++];
            }else {
                arr[index++] = left[i++];
            }
        }

        while (i < leftLen){
            arr[index++] = left[i++];
        }

        while (j < rightLen){
            arr[index++] = right[j++];
        }

        return arr;
    }
时间复杂度平均情况时间复杂度最好情况时间复杂度最坏情况空间复杂度稳定性
O(nlogn)O(nlogn)O(nlogn)O(n)稳定
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值