To create a sorted merged array of two unsorted arrays, at first, let us create two unsorted arrays−
int[] arr1 = new int[] {50, 22, 15, 40, 65, 75}; int[] arr2 = new int[] {60, 45, 10, 20, 35, 56};
Let us now create a new resultant array, that would have the merged array−
Example
int count1 = arr1.length; int count2 = arr2.length; int [] resArr = new int[count1 + count2]; Now, we will merge both the arrays in the resultant array resArr: while (i < arr1.length){ resArr[k] = arr1[i]; i++; k++; } while (j < arr2.length){ resArr[k] = arr2[j]; j++; k++; }
Let us now see the complete example
Example
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Demo { public static void main(String[] args){ int[] arr1 = new int[] {50, 22, 15, 40, 65, 75}; int[] arr2 = new int[] {60, 45, 10, 20, 35, 56}; System.out.println("1st Array = "+Arrays.toString(arr1)); System.out.println("2nd Array = "+Arrays.toString(arr2)); int count1 = arr1.length; int count2 = arr2.length; int [] resArr = new int[count1 + count2]; int i=0, j=0, k=0; while (i < arr1.length) { resArr[k] = arr1[i]; i++; k++; } while (j < arr2.length) { resArr[k] = arr2[j]; j++; k++; } Arrays.sort(resArr); System.out.println("Sorted Merged Array = "+Arrays.toString(resArr)); } }
Output
1st Array = [50, 22, 15, 40, 65, 75] 2nd Array = [60, 45, 10, 20, 35, 56] Sorted Merged Array = [10, 15, 20, 22, 35, 40, 45, 50, 56, 60, 65, 75]