diff --git a/src/main/java/com/thealgorithms/sorts/PostmanSort.java b/src/main/java/com/thealgorithms/sorts/PostmanSort.java new file mode 100644 index 000000000000..2226db222ef7 --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/PostmanSort.java @@ -0,0 +1,43 @@ +package com.thealgorithms.sorts; + +/** + * Postman Sort Algorithm Implementation + * + * @see Postman Sort Algorithm + */ +public class PostmanSort implements SortAlgorithm { + + @Override + public > T[] sort(T[] array) { + if (array == null || array.length <= 1) { + return array; + } + postmanSort(array); + return array; + } + + private > void postmanSort(T[] array) { + int n = array.length; + double gapFactor = 1.3; + int gap = (int) (n / gapFactor); + + while (gap > 0) { + for (int i = gap; i < n; i++) { + T temp = array[i]; + int j = i; + while (j >= gap && SortUtils.greater(array[j - gap], temp)) { + array[j] = array[j - gap]; + j -= gap; + } + array[j] = temp; + } + if (gap == 1) { + break; + } + gap = (int) (gap / gapFactor); + if (gap < 1) { + gap = 1; + } + } + } +} diff --git a/src/test/java/com/thealgorithms/sorts/PostmanSortTest.java b/src/test/java/com/thealgorithms/sorts/PostmanSortTest.java new file mode 100644 index 000000000000..0f8f349bfc02 --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/PostmanSortTest.java @@ -0,0 +1,8 @@ +package com.thealgorithms.sorts; + +public class PostmanSortTest extends SortingAlgorithmTest { + @Override + SortAlgorithm getSortAlgorithm() { + return new PostmanSort(); + } +}