Repository: TheAlgorithms/Java
Pull request #5288 (2024-07-13 08:49:22)

feat: add `PatienceSort`
Implementation for PatienceSort

Adding standard test for it

Update DIRECTORY.md

<!--
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/5288?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 `97.29730%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 40.62%. Comparing base [(`2d6c39c`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/2d6c39ce100855c87b41f0c3594586ba7fdd6fce?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`c4eede7`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c4eede7b5f21dc85703820246dc9c1584c8e5b13?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5288?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ain/java/com/thealgorithms/sorts/PatienceSort.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5288?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fsorts%2FPatienceSort.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zb3J0cy9QYXRpZW5jZVNvcnQuamF2YQ==) | 97.29% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5288?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    #5288      +/-   ##
============================================
+ Coverage     40.50%   40.62%   +0.12%     
- Complexity     2494     2506      +12     
============================================
  Files           519      520       +1     
  Lines         15470    15507      +37     
  Branches       2950     2957       +7     
============================================
+ Hits           6266     6300      +34     
- Misses         8915     8916       +1     
- Partials        289      291       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5288?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).

alxkm: This PR provide implementation for this [issue](https://github.com/TheAlgorithms/Java/issues/5291)

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 0c14970b..7e726f31 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -511,6 +511,7 @@
             * [MergeSortRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java)
             * [OddEvenSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/OddEvenSort.java)
             * [PancakeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PancakeSort.java)
+            * [PatienceSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PatienceSort.java)
             * [PigeonholeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java)
             * [QuickSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/QuickSort.java)
             * [RadixSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/RadixSort.java)
@@ -881,6 +882,7 @@
             * [MergeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortTest.java)
             * [OddEvenSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java)
             * [PancakeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PancakeSortTest.java)
+            * [PatienceSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java)
             * [QuickSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/QuickSortTest.java)
             * [RadixSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/RadixSortTest.java)
             * [SelectionSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java)
diff --git a/src/main/java/com/thealgorithms/sorts/PatienceSort.java b/src/main/java/com/thealgorithms/sorts/PatienceSort.java
new file mode 100644
index 00000000..52ed30d5
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/PatienceSort.java
@@ -0,0 +1,112 @@
+package com.thealgorithms.sorts;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.PriorityQueue;
+
+/**
+ * This class implements the Patience Sort algorithm. Patience Sort is a sorting algorithm that
+ * is particularly good for sorting sequences that are already partially sorted.
+ */
+public class PatienceSort implements SortAlgorithm {
+
+    /**
+     * Sorts an array of comparable elements using the Patience Sort algorithm.
+     *
+     * @param array the array to be sorted
+     * @param <T> the type of elements in the array, must be comparable
+     * @return the sorted array
+     */
+    @Override
+    public <T extends Comparable<T>> T[] sort(T[] array) {
+        if (array.length == 0) {
+            return array;
+        }
+
+        final List<List<T>> piles = formPiles(array);
+        final PriorityQueue<PileNode<T>> pq = mergePiles(piles);
+        extractPiles(array, pq);
+
+        return array;
+    }
+
+    /**
+     * Forms piles from the given array. Each pile is a list of elements where
+     * each element is smaller than the one before it. Binary search is used
+     * to find the appropriate pile for each element.
+     *
+     * @param array the array of elements to be organized into piles
+     * @param <T> the type of elements in the array, must be comparable
+     * @return a list of piles
+     */
+    private static <T extends Comparable<T>> List<List<T>> formPiles(final T[] array) {
+        final List<List<T>> piles = new ArrayList<>();
+        final List<T> lastElements = new ArrayList<>();
+
+        for (T x : array) {
+            int pos = Collections.binarySearch(lastElements, x);
+            if (pos < 0) {
+                pos = -pos - 1;
+            }
+
+            if (pos < piles.size()) {
+                piles.get(pos).add(x);
+                lastElements.set(pos, x);
+            } else {
+                List<T> newPile = new ArrayList<>();
+                newPile.add(x);
+                piles.add(newPile);
+                lastElements.add(x);
+            }
+        }
+
+        return piles;
+    }
+
+    /**
+     * Merges the piles into a priority queue where the smallest elements are
+     * prioritized.
+     *
+     * @param piles the list of piles to be merged
+     * @param <T> the type of elements in the piles, must be comparable
+     * @return a priority queue containing the top element of each pile
+     */
+    private static <T extends Comparable<T>> PriorityQueue<PileNode<T>> mergePiles(final List<List<T>> piles) {
+        PriorityQueue<PileNode<T>> pq = new PriorityQueue<>();
+        for (List<T> pile : piles) {
+            pq.add(new PileNode<>(pile.removeLast(), pile));
+        }
+        return pq;
+    }
+
+    /**
+     * Extracts elements from the priority queue to form the sorted array.
+     *
+     * @param array the array to be filled with sorted elements
+     * @param pq the priority queue containing the elements to be extracted
+     * @param <T> the type of elements in the array, must be comparable
+     */
+    private static <T extends Comparable<T>> void extractPiles(final T[] array, final PriorityQueue<PileNode<T>> pq) {
+        int index = 0;
+        while (!pq.isEmpty()) {
+            PileNode<T> node = pq.poll();
+            array[index++] = node.value;
+            if (!node.pile.isEmpty()) {
+                pq.add(new PileNode<>(node.pile.removeLast(), node.pile));
+            }
+        }
+    }
+
+    /**
+     * A helper record representing a node in the priority queue.
+     *
+     * @param <T> the type of elements in the node, must be comparable
+     */
+    private record PileNode<T extends Comparable<T>>(T value, List<T> pile) implements Comparable<PileNode<T>> {
+        @Override
+        public int compareTo(PileNode<T> other) {
+            return this.value.compareTo(other.value);
+        }
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java b/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java
new file mode 100644
index 00000000..f3cf7874
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java
@@ -0,0 +1,8 @@
+package com.thealgorithms.sorts;
+
+public class PatienceSortTest extends SortingAlgorithmTest {
+    @Override
+    SortAlgorithm getSortAlgorithm() {
+        return new PatienceSort();
+    }
+}