CodexBloom - Programming Q&A Platform

Unexpected Behavior in Merge Sort Implementation in Java - Fails on Large Datasets

👀 Views: 93 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
sorting merge-sort performance Java

I've hit a wall trying to I need some guidance on I'm converting an old project and After trying multiple solutions online, I still can't figure this out... I'm currently working on a merge sort implementation in Java, but I'm encountering unexpected behavior when sorting large datasets. The algorithm seems to work fine for smaller arrays, but when I input an array of size 10,000 or more, it appears to hang or take excessively long to finish. I've confirmed that the original array is being split correctly, but I suspect there might be an issue in the merging process. Here's the code I'm using: ```java public class MergeSort { public static void mergeSort(int[] array) { if (array.length < 2) return; 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++]; } } } ``` I've tested the algorithm with various sizes of input, and it consistently performs well for small arrays but slows down significantly for larger ones, often seeming to hang indefinitely. My current setup is using Java 11.0.10, and I'm running this on an Intel i7 processor with 16GB of RAM, so I don't think it's a hardware limitation. To troubleshoot, I added some print statements to log the progress, and I noticed that it hangs after merging the left and right arrays, specifically during the merging. I also considered the possibility of running out of stack space due to too many recursive calls, but increasing the stack size didn't yield any improvements. Any insights on what could be causing this behavior or suggestions on how to optimize the merge process would be greatly appreciated! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. My team is using Java for this microservice. For context: I'm using Java on Debian.