diff --git a/java/merge-sorted-array.java b/java/merge-sorted-array.java new file mode 100644 index 0000000..65fcf47 --- /dev/null +++ b/java/merge-sorted-array.java @@ -0,0 +1,25 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + // Shift numbers to right + for (int i = m - 1, k = nums1.length - 1; i >= 0; --i, --k) { + nums1[k] = nums1[i]; + } + + // Merge them + int j = 0, k = 0; + for (int i = nums1.length - m; i < nums1.length && j < n; ++k) { + if (nums1[i] < nums2[j]) { + nums1[k] = nums1[i]; + ++i; + } else { + nums1[k] = nums2[j]; + ++j; + } + } + + // Add the remainder + for (; j < n; ++j, ++k) { + nums1[k] = nums2[j]; + } + } +}