Repository: TheAlgorithms/Java
Pull request #5277 (2024-07-07 16:31:19)

refactor: `MergeSortNoExtraSpace`
Refactor MergeSortNoExtraSpace

Changing naming

Adding test

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5277?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 40.30%. Comparing base [(`96e59e0`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/96e59e063a3819389d94320fe1c8d5c915e0634b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`e3f2910`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/e3f2910beb079d4a9d98d27bb3caa46cefa8abdd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5277      +/-   ##
============================================
+ Coverage     40.06%   40.30%   +0.23%     
- Complexity     2467     2478      +11     
============================================
  Files           519      519              
  Lines         15481    15471      -10     
  Branches       2952     2950       -2     
============================================
+ Hits           6203     6236      +33     
+ Misses         8987     8944      -43     
  Partials        291      291              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5277?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
index 290c2df5..7aa3b56e 100644
--- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
+++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
@@ -1,73 +1,88 @@
 package com.thealgorithms.sorts;
 
 import java.util.Arrays;
-import java.util.Scanner;
 
-/*This code implements the mergeSort algorithm without extra space
-For understanding about mergesort visit :https://www.geeksforgeeks.org/merge-sort/
+/**
+ * Implementation of Merge Sort without using extra space for merging.
+ * This implementation performs in-place merging to sort the array of integers.
  */
 public final class MergeSortNoExtraSpace {
     private MergeSortNoExtraSpace() {
     }
 
-    public static void callMergeSort(int[] a, int n) {
-        int maxele = Arrays.stream(a).max().getAsInt() + 1;
-        mergeSort(a, 0, n - 1, maxele);
+    /**
+     * Sorts the array using in-place merge sort algorithm.
+     *
+     * @param array the array to be sorted
+     * @return the sorted array
+     * @throws IllegalArgumentException If the array contains negative numbers.
+     */
+    public static int[] sort(int[] array) {
+        if (array.length == 0) {
+            return array;
+        }
+        if (Arrays.stream(array).anyMatch(s -> s < 0)) {
+            throw new IllegalArgumentException("Implementation cannot sort negative numbers.");
+        }
+
+        final int maxElement = Arrays.stream(array).max().getAsInt() + 1;
+        mergeSort(array, 0, array.length - 1, maxElement);
+        return array;
     }
 
-    public static void mergeSort(int[] a, int start, int end, int maxele) { // this function divides the array into 2 halves
+    /**
+     * Recursively divides the array into two halves, sorts and merges them.
+     *
+     * @param array  the array to be sorted
+     * @param start  the starting index of the array
+     * @param end    the ending index of the array
+     * @param maxElement the value greater than any element in the array, used for encoding
+     */
+    public static void mergeSort(int[] array, int start, int end, int maxElement) {
         if (start < end) {
-            int mid = (start + end) / 2;
-            mergeSort(a, start, mid, maxele);
-            mergeSort(a, mid + 1, end, maxele);
-            implementMergeSort(a, start, mid, end, maxele);
+            final int middle = (start + end) >>> 1;
+            mergeSort(array, start, middle, maxElement);
+            mergeSort(array, middle + 1, end, maxElement);
+            merge(array, start, middle, end, maxElement);
         }
     }
 
-    public static void implementMergeSort(int[] a, int start, int mid, int end,
-        int maxele) { // implementation of mergesort
+    /**
+     * Merges two sorted subarrays [start...middle] and [middle+1...end] in place.
+     *
+     * @param array  the array containing the subarrays to be merged
+     * @param start  the starting index of the first subarray
+     * @param middle    the ending index of the first subarray and starting index of the second subarray
+     * @param end    the ending index of the second subarray
+     * @param maxElement the value greater than any element in the array, used for encoding
+     */
+    private static void merge(int[] array, int start, int middle, int end, int maxElement) {
         int i = start;
-        int j = mid + 1;
+        int j = middle + 1;
         int k = start;
-        while (i <= mid && j <= end) {
-            if (a[i] % maxele <= a[j] % maxele) {
-                a[k] = a[k] + (a[i] % maxele) * maxele;
+        while (i <= middle && j <= end) {
+            if (array[i] % maxElement <= array[j] % maxElement) {
+                array[k] = array[k] + (array[i] % maxElement) * maxElement;
                 k++;
                 i++;
             } else {
-                a[k] = a[k] + (a[j] % maxele) * maxele;
+                array[k] = array[k] + (array[j] % maxElement) * maxElement;
                 k++;
                 j++;
             }
         }
-        while (i <= mid) {
-            a[k] = a[k] + (a[i] % maxele) * maxele;
+        while (i <= middle) {
+            array[k] = array[k] + (array[i] % maxElement) * maxElement;
             k++;
             i++;
         }
         while (j <= end) {
-            a[k] = a[k] + (a[j] % maxele) * maxele;
+            array[k] = array[k] + (array[j] % maxElement) * maxElement;
             k++;
             j++;
         }
         for (i = start; i <= end; i++) {
-            a[i] = a[i] / maxele;
-        }
-    }
-
-    public static void main(String[] args) {
-        Scanner inp = new Scanner(System.in);
-        System.out.println("Enter array size");
-        int n = inp.nextInt();
-        int[] a = new int[n];
-        System.out.println("Enter array elements");
-        for (int i = 0; i < n; i++) {
-            a[i] = inp.nextInt();
-        }
-        callMergeSort(a, n);
-        for (int i = 0; i < a.length; i++) {
-            System.out.print(a[i] + " ");
+            array[i] = array[i] / maxElement;
         }
-        inp.close();
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java b/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java
new file mode 100644
index 00000000..5677a7c9
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java
@@ -0,0 +1,34 @@
+package com.thealgorithms.sorts;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class MergeSortNoExtraSpaceTest {
+    record TestCase(int[] inputArray, int[] expectedArray) {
+    }
+
+    static Stream<TestCase> provideTestCases() {
+        return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {1}, new int[] {1}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}),
+            new TestCase(new int[] {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}, new int[] {1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9}), new TestCase(new int[] {4, 2, 4, 3, 2, 1, 5}, new int[] {1, 2, 2, 3, 4, 4, 5}), new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}),
+            new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {1, 2, 3, 1, 2, 3, 1, 2, 3}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 3}),
+            new TestCase(new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), new TestCase(new int[] {2, 1}, new int[] {1, 2}), new TestCase(new int[] {1, 3, 2}, new int[] {1, 2, 3}));
+    }
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void testCountingSort(TestCase testCase) {
+        int[] outputArray = MergeSortNoExtraSpace.sort(testCase.inputArray);
+        assertArrayEquals(testCase.expectedArray, outputArray);
+    }
+
+    @Test
+    public void testNegativeNumbers() {
+        int[] arrayWithNegatives = {1, -2, 3, -4};
+        assertThrows(IllegalArgumentException.class, () -> MergeSortNoExtraSpace.sort(arrayWithNegatives));
+    }
+}