I want to implement a merge with sorting 2 arrays. My main methods and sorting method:

public static void main(String[] args) throws Exception { int [] arr1 = {1,2}; int [] arr2 = {5,9,2,7,11,22}; System.out.println(Arrays.toString(mergeArrays(arr1,arr2))); } public static int[] mergeArrays(int[] a1, int[] a2) { int k=0, i=0, g =0; int lenght =a1.length + a2.length; System.out.println(lenght); int res_mas [] = new int [lenght]; while(g!=lenght){ if(k<a1.length){ res_mas[g] = a1 [k]; } g++; if(i<a2.length){ res_mas[g] = a2 [i]; } g++; Arrays.sort(res_mas); k++; i++; } return res_mas; } 

In the console, I get the following:

  8 [0, 0, 0, 0, 1, 2, 5, 7] 

Please explain what could be a mistake. I have 2 assumptions, either in the logic of my code cant, or the sort() method has some nuance that I don’t know

    2 answers 2

    1. The problem is that if the array is over, in this case, the first one, then you increase g by one and proceed to the next check. Because here is an array of elements of a primitive type, then there is a default value of 0 , which will be added to your array.

    2. strange after each pass to do sorting. then it's easier to first fill all elements into one array and then do sort

    3. The idea of ​​sorting: if 2 sorted arrays are fed to the input, then at each step it is easier to compare the current elements of the original arrays with each other, add one that is larger (or less, depending on the order in which you want the elements to be), increase by 1 index of the array, the element of which was filled in with the new array and move on to the next step. It is clear that at every step it is necessary to check whether the elements in the source arrays have run out.

    PS For such cases, in order to understand what the problem is, I advise you to use Debug mode

      You can cut a little.

       return Arrays.sort(ArrayUtils.addAll(first, second));