简体   繁体   中英

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. 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; better to set it to a3[min_index] = Integer.MAX_VALUE; since there might be elements which are greater than 999999.

You can use Java Streams, a special kind of collections:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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