首页 > 解决方案 > Java 将两个数组合并为一个并对其进行排序

问题描述

我的任务是将两个数组连接成一个数组并对其进行排序。我已经连接了数组,但无法对其进行排序。
我的想法:创建一个新数组。在通过循环的连接数组中,找到最小的元素,将其推送到一个新数组中,最后使其成为最大数。但是,这种方法行不通。
我的代码:

public class Concat_arrays {
public static void main(String[] args) {
    int[] a1 = {4, 5, 3, 2, 1};
    int[] a2 = {10, 29, 0};
    int[] a3 = new int[a2.length+a1.length];

    int index = 0;
    for (int i = index; i<a1.length; i++) {
        a3[i] = a1[i];
        index++;
    }

    int indexA2 = 0;
    while (indexA2<a2.length) {
        a3[index] = a2[indexA2];
        index++;
        indexA2++;
    }

    int[] a4 = new int[a3.length];

    for (int i = 0; i<a3.length; i++) {
        int min_index = getMin(a3);
        a4[i] = a3[min_index];
        a3[min_index] = 999999;
    }




}

public static int getMin(int[] array) {
    int min_element = 0;
    int min_element_index = 0;

    for (int i = 0; i<array.length; i++) {
        if (min_element>=array[i]) {
            min_element_index = i;
        }
    }
    return min_element_index;
}

输出:

4
999999
999999
999999
999999
999999
999999
999999

标签: javaarrayssorting

解决方案


你的想法是正确的,但你的getMin方法是不正确的。我在下面更新了它。(你的想法可以改进)

public static int getMin(int[] array) {
    int min_element = Integer.MAX_VALUE; // Do not set it to 0 since there might be elements that has the value of 0
    int min_element_index = 0; 
    for (int i = 0; i < array.length; i++) {
        if (min_element >= array[i]) {
            min_element = array[i]; // You have to update your minimum element
            min_element_index = i;
        }
    }
    return min_element_index;
}

同样在这部分中a3[min_index] = 999999;最好将其设置为,a3[min_index] = Integer.MAX_VALUE;因为可能存在大于 999999 的元素。


推荐阅读