|
| 1 | +/** |
| 2 | + * The {@code MergeSortedArray} class provides a method to merge two sorted integer arrays |
| 3 | + * into a single sorted array. The merged result is printed to the standard output. |
| 4 | + * |
| 5 | + * <p> |
| 6 | + * Example usage: |
| 7 | + * <pre> |
| 8 | + * int[] nums1 = {1, 3, 5, 7}; |
| 9 | + * int[] nums2 = {2, 4, 6, 8}; |
| 10 | + * MergeSortedArray.merge(nums1, nums2); |
| 11 | + * // Output: 1 2 3 4 5 6 7 8 |
| 12 | + * </pre> |
| 13 | + * </p> |
| 14 | + * |
| 15 | + * <p> |
| 16 | + * The merging is performed in descending order from the end of both arrays, |
| 17 | + * and the result is stored in a new array before being printed. |
| 18 | + * </p> |
| 19 | + * |
| 20 | + * <p> |
| 21 | + * Note: The original arrays {@code nums1} and {@code nums2} are not modified. |
| 22 | + * </p> |
| 23 | + */ |
| 24 | +public class MergeSortedArray { |
| 25 | + public static void merge(int[] nums1, int[] nums2) { |
| 26 | + int l1 = nums1.length - 1; |
| 27 | + int l2 = nums2.length - 1; |
| 28 | + int i = nums1.length + nums2.length - 1; |
| 29 | + int[] result = new int[i + 1]; |
| 30 | + while (l1 >= 0 && l2 >= 0 && i >= 0) { |
| 31 | + if (nums1[l1] > nums2[l2]) { |
| 32 | + result[i--] = nums1[l1--]; |
| 33 | + } else { |
| 34 | + result[i--] = nums2[l2--]; |
| 35 | + } |
| 36 | + } |
| 37 | + while (l1 >= 0) { |
| 38 | + result[i--] = nums1[l1--]; |
| 39 | + } |
| 40 | + while (l2 >= 0) { |
| 41 | + result[i--] = nums2[l2--]; |
| 42 | + } |
| 43 | + for (int j = 0; j < result.length; j++) { |
| 44 | + System.out.print(result[j] + " "); |
| 45 | + } |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String args[]) { |
| 50 | + int[] nums1 = { 1, 3, 5, 7 }; |
| 51 | + int[] nums2 = { 2, 4, 6, 8 }; |
| 52 | + merge(nums1, nums2); |
| 53 | + } |
| 54 | +} |
0 commit comments