Repository: TheAlgorithms/Java
Pull request #5624 (2024-10-07 09:39:38)

Add SortStack.java new algorithm
<!--
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/5624?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `92.85714%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 54.77%. Comparing base [(`f34fe4d`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f34fe4d8408ac35cef900cfae022ffadfc007ea3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`7bd23b5`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7bd23b53a35367ebf6fc87133b54774678576a6e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 6 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5624?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [.../main/java/com/thealgorithms/stacks/SortStack.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5624?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FSortStack.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvU29ydFN0YWNrLmphdmE=) | 92.85% | [1 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5624?src=pr&el=tree&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    #5624      +/-   ##
============================================
+ Coverage     54.56%   54.77%   +0.21%     
- Complexity     3413     3458      +45     
============================================
  Files           535      539       +4     
  Lines         15383    15597     +214     
  Branches       2935     2961      +26     
============================================
+ Hits           8393     8543     +150     
- Misses         6637     6696      +59     
- Partials        353      358       +5     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5624?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/DIRECTORY.md b/DIRECTORY.md
index 228735aa..9fb11129 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -267,6 +267,7 @@
             * [SumOfSubset](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java)
             * [Tribonacci](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java)
             * [UniquePaths](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java)
+            * [UniqueSubsequencesCount](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java)
             * [WildcardMatching](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java)
             * [WineProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java)
           * geometry
@@ -566,6 +567,7 @@
             * [NextSmallerElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java)
             * [PostfixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java)
             * [PrefixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java)
+            * [SortStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/SortStack.java)
             * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java)
           * strings
             * [AhoCorasick](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/AhoCorasick.java)
@@ -794,6 +796,7 @@
             * [SumOfSubsetTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java)
             * [TribonacciTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java)
             * [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/UniquePathsTests.java)
+            * [UniqueSubsequencesCountTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java)
             * [WildcardMatchingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java)
           * geometry
             * [GrahamScanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java)
@@ -1027,6 +1030,7 @@
             * [NextSmallerElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java)
             * [PostfixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java)
             * [PrefixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java)
+            * [SortStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/SortStackTest.java)
             * [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
           * strings
             * [AhoCorasickTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/SortStack.java b/src/main/java/com/thealgorithms/stacks/SortStack.java
new file mode 100644
index 00000000..d07d1a5f
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/SortStack.java
@@ -0,0 +1,60 @@
+package com.thealgorithms.stacks;
+
+import java.util.Stack;
+
+/**
+ * A utility class that provides a method to sort a stack using recursion.
+ * The elements are sorted in ascending order, with the largest element at the top.
+ * This algorithm is implemented using only recursion and the original stack,
+ * without utilizing any additional data structures apart from the stack itself.
+ */
+public final class SortStack {
+    private SortStack() {
+    }
+
+    /**
+     * Sorts the given stack in ascending order using recursion.
+     * The sorting is performed such that the largest element ends up on top of the stack.
+     * This method modifies the original stack and does not return a new stack.
+     *
+     * The algorithm works as follows:
+     * 1. Remove the top element.
+     * 2. Recursively sort the remaining stack.
+     * 3. Insert the removed element back into the sorted stack at the correct position.
+     *
+     * @param stack The stack to be sorted, containing Integer elements.
+     * @throws IllegalArgumentException if the stack contains `null` elements.
+     */
+    public static void sortStack(Stack<Integer> stack) {
+        if (stack.isEmpty()) {
+            return;
+        }
+
+        int top = stack.pop();
+        sortStack(stack);
+        insertInSortedOrder(stack, top);
+    }
+
+    /**
+     * Helper method to insert an element into the correct position in a sorted stack.
+     * This method is called recursively to place the given element into the stack
+     * such that the stack remains sorted in ascending order.
+     *
+     * The element is inserted in such a way that all elements below it are smaller
+     * (if the stack is non-empty), and elements above it are larger, maintaining
+     * the ascending order.
+     *
+     * @param stack The stack in which the element needs to be inserted.
+     * @param element The element to be inserted into the stack in sorted order.
+     */
+    private static void insertInSortedOrder(Stack<Integer> stack, int element) {
+        if (stack.isEmpty() || element > stack.peek()) {
+            stack.push(element);
+            return;
+        }
+
+        int top = stack.pop();
+        insertInSortedOrder(stack, element);
+        stack.push(top);
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/SortStackTest.java b/src/test/java/com/thealgorithms/stacks/SortStackTest.java
new file mode 100644
index 00000000..b9f2f1b6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/SortStackTest.java
@@ -0,0 +1,77 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Stack;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class SortStackTest {
+
+    private Stack<Integer> stack;
+
+    @BeforeEach
+    public void setUp() {
+        stack = new Stack<>();
+    }
+
+    @Test
+    public void testSortEmptyStack() {
+        SortStack.sortStack(stack);
+        assertTrue(stack.isEmpty()); // An empty stack should remain empty
+    }
+
+    @Test
+    public void testSortSingleElementStack() {
+        stack.push(10);
+        SortStack.sortStack(stack);
+        assertEquals(1, stack.size());
+        assertEquals(10, (int) stack.peek()); // Single element should remain unchanged
+    }
+
+    @Test
+    public void testSortAlreadySortedStack() {
+        stack.push(1);
+        stack.push(2);
+        stack.push(3);
+        stack.push(4);
+        SortStack.sortStack(stack);
+
+        assertEquals(4, stack.size());
+        assertEquals(4, (int) stack.pop());
+        assertEquals(3, (int) stack.pop());
+        assertEquals(2, (int) stack.pop());
+        assertEquals(1, (int) stack.pop());
+    }
+
+    @Test
+    public void testSortUnsortedStack() {
+        stack.push(3);
+        stack.push(1);
+        stack.push(4);
+        stack.push(2);
+        SortStack.sortStack(stack);
+
+        assertEquals(4, stack.size());
+        assertEquals(4, (int) stack.pop());
+        assertEquals(3, (int) stack.pop());
+        assertEquals(2, (int) stack.pop());
+        assertEquals(1, (int) stack.pop());
+    }
+
+    @Test
+    public void testSortWithDuplicateElements() {
+        stack.push(3);
+        stack.push(1);
+        stack.push(3);
+        stack.push(2);
+        SortStack.sortStack(stack);
+
+        assertEquals(4, stack.size());
+        assertEquals(3, (int) stack.pop());
+        assertEquals(3, (int) stack.pop());
+        assertEquals(2, (int) stack.pop());
+        assertEquals(1, (int) stack.pop());
+    }
+}