Skip to content

Commit f158286

Browse files
committed
Add PostmanSort algorithm
- Implements Postman Sort using gap-based insertion approach - Adaptive gap reduction with shrink factor of 1.3 - Includes comprehensive test suite extending SortingAlgorithmTest
1 parent 9484c7e commit f158286

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Postman Sort Algorithm Implementation
7+
*
8+
* @see <a href="https://en.wikipedia.org/wiki/Postman_sort">Postman Sort Algorithm</a>
9+
*/
10+
public class PostmanSort implements SortAlgorithm {
11+
12+
@Override
13+
public <T extends Comparable<T>> T[] sort(T[] array) {
14+
if (array == null || array.length <= 1) {
15+
return array;
16+
}
17+
postmanSort(array);
18+
return array;
19+
}
20+
21+
private <T extends Comparable<T>> void postmanSort(T[] array) {
22+
int n = array.length;
23+
double gapFactor = 1.3;
24+
int gap = (int) (n / gapFactor);
25+
26+
while (gap > 0) {
27+
for (int i = gap; i < n; i++) {
28+
T temp = array[i];
29+
int j = i;
30+
while (j >= gap && SortUtils.greater(array[j - gap], temp)) {
31+
array[j] = array[j - gap];
32+
j -= gap;
33+
}
34+
array[j] = temp;
35+
}
36+
if (gap == 1) {
37+
break;
38+
}
39+
gap = (int) (gap / gapFactor);
40+
if (gap < 1) {
41+
gap = 1;
42+
}
43+
}
44+
}
45+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class PostmanSortTest extends SortingAlgorithmTest {
4+
@Override
5+
SortAlgorithm getSortAlgorithm() {
6+
return new PostmanSort();
7+
}
8+
}

0 commit comments

Comments
 (0)