To merge two sorted arrays into a single sorted bigger array in Java, you can use the Arrays.copyOf
method to create a new larger array, and then use two pointers to iterate through the two input arrays and copy the elements to the new array in sorted order.
Here is an example of how you can merge two sorted arrays into a single sorted bigger array in Java:
refer to:lautturi.comimport java.util.Arrays; public class Main { public static void main(String[] args) { int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {2, 4, 6, 8, 10}; int[] mergedArray = mergeArrays(array1, array2); System.out.println(Arrays.toString(mergedArray)); } public static int[] mergeArrays(int[] array1, int[] array2) { int[] mergedArray = Arrays.copyOf(array1, array1.length + array2.length); int i = 0; int j = 0; int k = 0; while (i < array1.length && j < array2.length) { if (array1[i] < array2[j]) { mergedArray[k] = array1[i]; i++; } else { mergedArray[k] = array2[j]; j++; } k++; } while (i < array1.length) { mergedArray[k] = array1[i]; i++; k++; } while (j < array2.length) { mergedArray[k] = array2[j]; j++; k++; } return mergedArray; } }
In this example, the mergeArrays
method takes two sorted arrays as input and returns a new sorted array that contains the elements of the two input arrays. The method first creates a new larger array using the Arrays.copyOf
method, and then uses two pointers i
and j
to iterate through the two input arrays. At each iteration, the method compares the elements at the current pointers and copies the smaller element to the new array. If one of the input arrays has been fully traversed, the method copies the remaining elements of the other array to the new array.
The main
method of the Main
class demonstrates how to use the mergeArrays
method to merge two sorted arrays and print the resulting array to the console.
Keep in mind that this approach has a time complexity of O(n), where n is the total number of elements in the two input arrays. It is also possible to use more efficient algorithms, such as merge sort, to merge the two arrays, but these algorithms may have a higher space complexity.