The task is to connect 2 arrays (sorted) into 1, and in such a way that it is immediately sorted. That is, if arrays {0, 2} and {1, 3} are fed to the input, then the output should be an array {0, 1, 2, 3}

public static int[] mergeArrays(int[] a1, int[] a2) { if (a1 == null) return a2; if (a2 == null) return a1; int[] r = new int[a1.length + a2.length]; for (int i = 0, a1Index = 0, a2Index = 0; i < r.length; ) { while (a1Index < a1.length && a1[a1Index] < a2[a2Index]) { r[i] = a1[a1Index]; a1Index++; i++; } r[i] = a2[a2Index]; a2Index++; i++; } return r; } 

For some reason, I vyprigivaet of the array.

  • Need to use exactly arrays to go and collections fit? - Vladislav Kuznetsov
  • arrays ... but I already found the problem ... trying to fix it - Oleksandr

3 answers 3

Something like this:

  public static int[] mergeArrays(int[] a1, int[] a2) { int[] r = new int[a1.length + a2.length]; int a1Ind = 0; int a2Ind = 0; for (int i = 0; i < r.length;i++ ) { if (a1Ind == a1.length) { System.arraycopy(a2,a2Ind,r, i, r.length-i); break; } if (a2Ind == a2.length) { System.arraycopy(a1, a1Ind, r, i, r.length-i); break; } if (a1[a1Ind]<=a2[a2Ind]){ r[i]=a1[a1Ind]; a1Ind++; }else { r[i]=a2[a2Ind]; a2Ind++; } } return r; } 

It seems to work ... if someone comes in and offers a better option, I will be grateful.

    I got this solution:

     private static int[] merge(int[] firstArray, int[] secondArray) { Objects.requireNonNull(firstArray); Objects.requireNonNull(secondArray); int[] result = new int[firstArray.length + secondArray.length]; int firstIndex = 0; int secondIndex = 0; int index = 0; while (firstIndex < firstArray.length && secondIndex < secondArray.length) if (firstArray[firstIndex] <= secondArray[secondIndex]) result[index++] = firstArray[firstIndex++]; else result[index++] = secondArray[secondIndex++]; if (index == result.length) return result; while (firstIndex < firstArray.length) result[index++] = firstArray[firstIndex++]; while (secondIndex < secondArray.length) result[index++] = secondArray[secondIndex++]; return result; } 

      Java 8

       int[] a1 = {0,2,5,8,9}; int[] a2 = {1,4,3,7,6}; int[] result = IntStream.concat(Arrays.stream(a1),Arrays.stream(a2)).sorted().toArray(); for (int i : result) { System.out.print(i + " "); } 

      0 1 2 3 4 5 6 7 8 9

      • Thank you for your reply. Keep in mind for the future. But in my case, I understood in the statement of the problem that the sorting could not be used, it was necessary to immediately scatter the elements into an array so that it did not need to be re-sorted. - Oleksandr