归并排序 java 实现

/**
     * 归并排序 两个数组都是有序的 否则需要先先排序
     * @param a
     * @param b
     */
    private static void mergerSort(int [] a,int [] b) {
        int[] tempArray = new int[a.length+b.length];//创建临时接受数组
        int tempCounter = 0;
        int firstIndex=0, secondIndex=0;
        while((firstIndex<a.length)&&(secondIndex<b.length)){
            if (a[firstIndex] < b[secondIndex]) {
                tempArray[tempCounter] = a[firstIndex];
                tempCounter++;
                firstIndex++;
            }
            else if (a[firstIndex] > b[secondIndex]) {
                tempArray[tempCounter] = b[secondIndex];
                tempCounter++;
                secondIndex++;
            }
            else {
                tempArray[tempCounter] = a[firstIndex];
                firstIndex++;
                tempCounter++;
            }
        }
        /**
         * 下面两种情况是当有一个数组已经完全放入了temp数组里面  
         * 已经失去比较对象,接下来的数字肯定是比前一个已经完全放入数组的最大的数还大,所以直接拷贝就可以了。
         */
        while (secondIndex < b.length) {
                tempArray[tempCounter] = b[secondIndex];
                secondIndex++;
                tempCounter++;
        }
        while (firstIndex<a.length) {
            tempArray[tempCounter] = a[firstIndex];
            firstIndex++;
            tempCounter++;
        }
        for (int j = 0; j < tempArray.length; j++) {
            System.out.print(tempArray[j]+" ");
        }
    }


    public static void main(String[] args) throws Exception {
        int[] a  = new int[]{1,2,4,9};
        int[] b  = new int[]{2,4,8};
        mergerSort(a, b);

    }

运行结果是:1 2 4 4 8 9

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值