Unexpected Infinite Loop in Merge Sort Implementation in Java - Issues with Base Case Check
I'm stuck on something that should probably be simple. I'm stuck on something that should probably be simple. I'm facing an issue with my Merge Sort implementation in Java where it occasionally leads to an infinite loop. I've implemented the algorithm recursively, but it seems like the base case is not being triggered correctly under certain conditions. Here's a snippet of my code: ```java public class MergeSort { public static void mergeSort(int[] array) { if (array.length < 2) { return; // Base case } int mid = array.length / 2; int[] left = Arrays.copyOfRange(array, 0, mid); int[] right = Arrays.copyOfRange(array, mid, array.length); mergeSort(left); mergeSort(right); merge(array, left, right); } private static void merge(int[] array, int[] left, int[] right) { int i = 0, j = 0, k = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) { array[k++] = left[i++]; } else { array[k++] = right[j++]; } } while (i < left.length) { array[k++] = left[i++]; } while (j < right.length) { array[k++] = right[j++]; } } } ``` When I run this code with an input array like `{5, 1, 4, 2, 8}`, it sorts correctly. However, with an array that has duplicate values, such as `{3, 3, 3, 3, 3}`, or an empty array `[]`, the program hangs indefinitely. I've double-checked the base case and it seems correct, but I suspect there might be an issue with how I'm handling the array slicing. Any insights into why this might be happening would be greatly appreciated, especially any edge cases I might be overlooking. I'm using Java 11 and have ensured that all necessary imports are included. Any ideas what could be causing this? I recently upgraded to Java latest. Any help would be greatly appreciated!