CodexBloom - Programming Q&A Platform

Issues with Implementing Merge Sort in Java - Unexpected Behavior with Duplicate Elements

👀 Views: 23 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
sorting merge-sort stability Java

I need help solving I've looked through the documentation and I'm still confused about After trying multiple solutions online, I still can't figure this out. I'm currently trying to implement a Merge Sort algorithm in Java, but I'm facing unexpected behavior when dealing with arrays that contain duplicate elements. My implementation sorts the array correctly most of the time, but on certain test cases with duplicates, the order of the equal elements seems to change, which is not the behavior I expected from a stable sorting algorithm. Here's the code I have: ```java public class MergeSort { public static void mergeSort(int[] array, int left, int right) { if (left < right) { int mid = (left + right) / 2; mergeSort(array, left, mid); mergeSort(array, mid + 1, right); merge(array, left, mid, right); } } private static void merge(int[] array, int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid; int[] L = new int[n1]; int[] R = new int[n2]; for (int i = 0; i < n1; i++) { L[i] = array[left + i]; } for (int j = 0; j < n2; j++) { R[j] = array[mid + 1 + j]; } int i = 0, j = 0; int k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { array[k] = L[i]; i++; } else { array[k] = R[j]; j++; } k++; } while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = R[j]; j++; k++; } } } ``` When I run the following code: ```java public static void main(String[] args) { int[] array = {4, 2, 2, 8, 3, 3, 1}; MergeSort.mergeSort(array, 0, array.length - 1); System.out.println(Arrays.toString(array)); } ``` I expect the output to maintain the order of duplicates, but I see that the two `3`s are sometimes swapped in position. I've checked the merge logic, but I'm not sure if I missed something regarding how duplicates should be handled. I've even run my code with Java 8 and updated the compiler settings, but the issue persists. Can anyone help me figure out why this is happening? Is there a specific change I need to make in the merge step to ensure stability in sorting? For context: I'm using Java on Ubuntu. Thanks in advance! This is part of a larger service I'm building. Any advice would be much appreciated. I'm developing on Ubuntu 22.04 with Java. Any help would be greatly appreciated! I'm coming from a different tech stack and learning Java. What would be the recommended way to handle this?