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