Merging two sorted arrays into a single sorted array.
Here’s an example of a Java program that merges two sorted arrays into a single sorted array:
import java.util.Arrays; public class MergeSortedArrays { public static int[] mergeArrays(int[] arr1, int[] arr2) { int n1 = arr1.length; int n2 = arr2.length; int[] mergedArray = new int[n1 + n2]; int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { mergedArray[k] = arr1[i]; i++; } else { mergedArray[k] = arr2[j]; j++; } k++; } while (i < n1) { mergedArray[k] = arr1[i]; i++; k++; } while (j < n2) { mergedArray[k] = arr2[j]; j++; k++; } return mergedArray; } public static void main(String[] args) { int[] arr1 = {1, 3, 5, 7, 9}; int[] arr2 = {2, 4, 6, 8, 10}; int[] mergedArray = mergeArrays(arr1, arr2); System.out.println("Merged Array: " + Arrays.toString(mergedArray)); } }
In this program, we define a `mergeArrays` function that takes in two sorted arrays, `arr1` and `arr2`, and returns a new merged and sorted array. We initialize a new array, `mergedArray`, with a size equal to the sum of the lengths of `arr1` and `arr2`.
We then use three pointers, `i`, `j`, and `k`, to iterate over `arr1`, `arr2`, and `mergedArray`, respectively. We compare the elements at the current indices `i` and `j` of `arr1` and `arr2` and place the smaller element into `mergedArray`. We increment `i` or `j` depending on which array’s element was chosen, and we increment `k` to move to the next position in `mergedArray`.
After one of the arrays is fully processed, we copy the remaining elements from the other array into `mergedArray`. Finally, we return the resulting `mergedArray`.
In the `main` function, we provide example arrays `arr1` and `arr2` to demonstrate the usage of the `mergeArrays` function. The merged and sorted array is then printed to the console.