如何按升序合并两个整数数组?

How to merge two integer arrays in ascending order?

如何按升序合并两个数组? 我有下面的代码,我需要按升序合并这个数组,它应该在一个单独的方法中。所以在这种情况下,方法应该 return {1, 4, 8, 9, 11, 12, 13}

public class MergingArrays {
    public static void main(String[] args) {
        int [] array1 = {4, 8, 12, 13};
        int [] array2 = {1, 9, 11};
        merge(array1, array2);
    } 
    public static int[] merge(int array1[], int array2[]) {

    }
}

假设您要合并两个已排序的数组,您可以这样做。

public static int[] merge(int array1[], int array2[]) {
    int i = 0, j = 0, k = 0;
    int size1 = array1.length;
    int size2 = array2.length;
    int[] result = new int[size1 + size2];

    while (i < size1 && j < size2) {
        if (array1[i] < array2[j]) {
            result[k++] = array1[i++];
        } else {
            result[k++] = array2[j++];
        }
    }

    // Store remaining elements
    while (i < size1) {
        result[k++] = array1[i++];
    }

    while (j < size2) {
        result[k++] = array2[j++];
    }
    
    return result;

}
public static int[] merge(int[] array1, int[] array2) {
        int totalElements = array1.length + array2.length, array2Index = 0;
        int[] toReturn = new int[totalElements];

        for (int i = 0; i < array1.length; i++) {
            toReturn[i] = array1[i];
        }
        for (int i = array1.length; i < totalElements; i++) {
            toReturn[i] = array2[array2Index++];
        }

        //Manual Ascending Array Sorting
        for (int i = 0; i < totalElements; i++) {
            for (int j = 0; j < totalElements; j++) {
                if(toReturn[i] < toReturn[j]) {
                    int temp = toReturn[i];
                    toReturn[i] = toReturn[j];
                    toReturn[j] = temp;
                }
            }
        }
        return toReturn;
    }

您可以使用 apache commons class 和 Collections 的排序功能 class

import org.apache.commons.lang.ArrayUtils;
import java.util.Collections;

public class MergingArrays {
    public static void main(String[] args) {
        int [] array1 = {4, 8, 12, 13};
        int [] array2 = {1, 9, 11};
        merge(array1, array2);
    } 
    public static int[] merge(int array1[], int array2[]) {
    return Collections.sort(ArrayUtils.addAll(array1, array2));
    }
}