Java: How do I efficiently merge two sorted arrays into one sorted array without using extra space?
I'm currently working on a Java project that requires me to merge two sorted arrays into one sorted array... The catch is that I need to do this in-place and without using extra space for another array. I know that merging is commonly done by creating a new array and populating it, but I'm trying to optimize for space efficiency. I have two sorted arrays: `array1` and `array2`. My current approach involves using two pointers to traverse both arrays, but Iโm running into issues with maintaining the order and properly placing elements. Hereโs what Iโve attempted so far: ```java public class ArrayMerger { public static void mergeSortedArrays(int[] array1, int[] array2) { int m = array1.length; int n = array2.length; int i = m - 1; // Pointer for array1 int j = n - 1; // Pointer for array2 int k = m + n - 1; // Pointer for the merged array while (j >= 0) { if (i >= 0 && array1[i] > array2[j]) { array1[k--] = array1[i--]; } else { array1[k--] = array2[j--]; } } } } ``` When I run this code, I'm getting an `ArrayIndexOutOfBoundsException` because I'm trying to access indexes in `array1` that are out of its bounds after merging. This happens especially when `array2` has smaller elements. I know that I should be careful about the boundaries, but I'm not quite sure how to handle cases where one of the arrays gets fully merged before the other. Any guidance on how to correctly manage the pointers and ensure I donโt run into index issues would be greatly appreciated. I'm using Java version 17. My team is using Java for this desktop app.