合并和排序两个数组Java?

use*_*164 4 java arrays sorting

所以基本上有两个独立的预分类数组,你必须将它们组合起来并对它们进行排序(当然没有sort()方法).这是我的代码:

public static void main(String[] args) {

    int a [] = {3,5,7,9,12,14, 15};
    int b [] = {6 ,7, 10};
    int j = 0;

    //output array should be 3,5,6,7,7,9,10,12,14,15

    int c [] = new int[a.length+b.length];//10 values

    for (int i = 0;i<b.length;i++){
        while(b[i]>a[j]){
            c[j] = a[j] ;
            j++;    
         }

        if(b[i] == a[j]){
            c[j] = b[i];
            c[j+1] = a[j];
        }

        c[j] = b[i];
        j++;
    }

    for(int i = 0;i<c.length;i++)
        System.out.println(c[i]);
    }
Run Code Online (Sandbox Code Playgroud)

我猜我得到的零是来自其中一个布尔(<&>)的错误,但我似乎无法弄明白.它适用于前4个,但是一旦我重复7个,它就会变得疯狂.

请帮助我理解,不要只是改变代码.

hat*_*enn 6

这应该是一个简单的方式:

public static void main(String[] args) {

    int a [] = {3,5,7,9,12,14, 15};
    int b [] = {6 ,7, 10};
    int j = 0, k = 0;

    //output array should be 3,5,6,7,7,9,10,12,14,15

    int c [] = new int[a.length+b.length];//10 values

    // we're filling c with the next appropriate number
    // we start with checking a[0] and b[0] till we add
    // all the elements
    for (int i = 0; i < c.length; i++) {
        // if both "a" and "b" have elements left to check
        if (j < a.length && k < b.length) {
            // check if "b" has a smaller element
            if (b[k] < a[j]) {
                // if so add it to "c"
                c[i] = b[k];
                k++;
            }
            // if "a" has a smaller element
            else {
                // add it to "c"
                c[i] = a[j];
                j++;
            }       
        }
        // if there are no more elements to check in "a"
        // but there are still elements to check in "b"
        else if (k < b.length) {
            // add those elements in "b" to "c"
            c[i] = b[k];
            k++;
        }
        // if there are no more elements to check in "b"
        // but there are still elements to check in "a"
        else {
            // add those elements in "a" to "c"
            c[i] = a[j];
            j++;
        }
    }

    for(int i = 0; i < c.length; i++)
        System.out.println(c[i]);
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.