Skip to content

Commit 07f5158

Browse files
authored
Create StalinSort.java
1 parent 2338428 commit 07f5158

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.sorts;
2+
3+
/**
4+
* Stalin Sort is a sorting algorithm that works by iterating through the array and
5+
* maintaining a sorted portion of the array at the beginning. If a number is encountered
6+
* that is smaller than the last number in the sorted portion, it is discarded (not added).
7+
* This algorithm is not stable and will not sort all elements correctly if there are
8+
* elements that violate the sort order.
9+
*
10+
* For more information, see:
11+
* https://en.wikipedia.org/wiki/Stalin_sort
12+
*/
13+
public class StalinSort implements SortAlgorithm {
14+
15+
@Override
16+
public <T extends Comparable<T>> T[] sort(T[] array) {
17+
if (array.length == 0) {
18+
return array;
19+
}
20+
21+
T[] result = (T[]) new Comparable[array.length];
22+
int index = 0;
23+
result[index++] = array[0];
24+
25+
for (int i = 1; i < array.length; i++) {
26+
if (SortUtils.less(result[index - 1], array[i])) {
27+
result[index++] = array[i];
28+
}
29+
}
30+
31+
return trimArray(result, index);
32+
}
33+
34+
private <T> T[] trimArray(T[] array, int length) {
35+
T[] trimmedArray = (T[]) new Comparable[length];
36+
System.arraycopy(array, 0, trimmedArray, 0, length);
37+
return trimmedArray;
38+
}
39+
}

0 commit comments

Comments
 (0)