两个有序数组组成一个有序的数组

package com.hzins.suanfa;

import java.util.Arrays;
/**
 * 
 * 两个有序数组组成一个有序的数组
 * 整个循环层数为1
 * 以其中一个数组做循环,注意另外一个的index是否溢出以及另外一个是否没有遍历完成
 * 
 * @author Administrator
 *
 */
public class Demo2 {
    /**
     * 
     * 1,3,5,7
     * 2,4,6,8
     * @param a
     * @param b
     */
    public static void sort(int[] a,int[] b){
        int temp[] = new int[a.length + b.length];
        int aIndex = 0;
        int bIndex =0;
        int k = 0;
        for(aIndex = 0;aIndex < a.length;){
            if(bIndex < b.length && (b[bIndex] < a[aIndex])){
                temp[k ++] = b[bIndex ++];
            }
            //两个可以合并成一个
//            else if(bIndex < b.length && (b[bIndex] >= a[aIndex])){
//                temp[k ++] = a[aIndex ++];
//            }
//            else{
//                temp[k ++] = a[aIndex ++];
//            }
            else{
                temp[k ++] = a[aIndex ++];
            }
            
        }
        while(bIndex <= b.length - 1){
            temp[k ++] = b[bIndex ++];
        }
        System.out.println(Arrays.toString(temp));
    }
    public static void main(String[] args) {
        int[] a = {1,3,5,7};
        int[] b = {2,4,6,8,9,10,11,12,13};
        sort(a, b);
    }
}
原文地址:https://www.cnblogs.com/caobojia/p/6785861.html