简体   繁体   English

Java将两个数组合并为一个并对其进行排序

[英]Java concatenate two arrays into one and sort it

My task is to concatenate two arrays into one and sort it. 我的任务是将两个数组合并为一个并对其进行排序。 I have already concatenated arrays, but can't sort it. 我已经串联了数组,但无法对其进行排序。
My idea: Create a new array. 我的主意:创建一个新数组。 In concatenated array through the loop, find the smallest element, push it to a new array and in the end, make it the largest number. 在循环中的串联数组中,找到最小的元素,将其推入新数组,最后,使其成为最大的数字。 However, this approach doesn't work. 但是,这种方法不起作用。
My Code: 我的代码:

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;
}

Output: 输出:

4
999999
999999
999999
999999
999999
999999
999999

You are on the right track on your idea, but your getMin method is incorrect. 您的想法正确getMin ,但getMin方法不正确。 I have updated it below. 我已经在下面更新了。 (Your idea can be improved) (您的想法可以改进)

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;
}

Also in this part a3[min_index] = 999999; 同样在这部分中, a3[min_index] = 999999; better to set it to a3[min_index] = Integer.MAX_VALUE; 最好将其设置为a3[min_index] = Integer.MAX_VALUE; since there might be elements which are greater than 999999. 因为可能存在大于999999的元素。

You can use Java Streams, a special kind of collections: 您可以使用Java Streams,这是一种特殊的集合:

int[] a1 = {4, 5, 3, 2, 1};
int[] a2 = {10, 29, 0};

Stream<Integer> a1Stream = Stream.of(4, 5, 3, 2, 1);
Stream<Integer> a2Stream = Stream.of(10, 29, 0);

Stream<Integer> finalArray = Stream.concat(a1Stream, a2Stream).sorted();
finalArray.forEach(s -> System.out.println(s));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM