This question already has answers here:
How to merge two sorted arrays into a sorted array? [closed]

(31 个回答)


3年前关闭。



public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arrA = {2,3,4};
        int[] arrB = {5,6,7,8};
        mergeArray(arrA,arrB);
    }
    static void mergeArray(int[] arrA,int[] arrB){

        int len = arrA.length+arrB.length;
        int lenA = arrA.length;
        int lenB = arrB.length;
        int a=0,b=0,c=0;
        int temp=0;
        int[] arrC = new int[len];
        for(int i=0; i < lenA; i++){
            arrC[i] = arrA[i];
        }
        for(int j=lenA,k=0; (k < lenB) && (j < len) ; j++,k++){
            arrC[j] = arrB[k];
        }
        for(int n=0; n < len ; n++){
            for(int m=0; m < len; m++ ){
                if(arrC[n] < arrC[m]){
                    temp  = arrC[n];
                    arrC[n] = arrC[m];
                    arrC[m] = temp;
                }
            }
        }
        for(int x : arrC){
            System.out.println(x);
        }
    }

结果:{2,3,4,5,6,7,8}

我正在尝试将这些值放入一个新数组中并再次对它们进行排序。谁能给我比这更好的解决方案。

最佳答案

我想起了上学的日子!这是解决方案!没有库,只有简单的代码!享受。

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int [] array1 = {5, 1, 4, 5, 7, 8, 1, 0, 4};
        int [] array2 = {4, 7, 1, 0, 9, 3};

        System.out.println("Array 1");
        print(array1);

        System.out.println("Array 2");
        print(array2);

        Arrays.sort(array1);
        Arrays.sort(array2);

        System.out.println("Sorted array 1");
        print(array1);

        System.out.println("Sorted array 2");
        print(array2);

        int [] mergedAndSortedArray = mergeSorted(array1, array2);

        System.out.println("Sorted merged array");
        print(mergedAndSortedArray);
    }

    private static void print(int [] array) {
        for (int i : array) {
            System.out.print(i + " ");
        }

        System.out.println("\n");
    }

    private static int [] mergeSorted(int [] array1, int [] array2) {
        int [] res = new int [array1.length + array2.length];

        int i = 0;
        int j = 0;
        int k = 0;

        //Do your homework. First loop until you reach end of either array, and then add the rest elements.

        return res;
    }
}

这是结果
Array 1
5 1 4 5 7 8 1 0 4

Array 2
4 7 1 0 9 3

Sorted array 1
0 1 1 4 4 5 5 7 8

Sorted array 2
0 1 3 4 7 9

Sorted merged array
0 0 1 1 1 3 4 4 4 5 5 7 7 8 9

更新

如果需要将 N 已排序数组合并为一个已排序数组,则可以将它们逐对递归合并(合并第一个和第二个数组,第三个和第四个数组,依此类推),然后再次,直到有两个数组,最后合并他们也是!

关于java - 任何人都可以给我更好的解决方案,将两个排序数组合并到另一个排序数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44592749/

10-12 00:38
查看更多