Skip to content

Commit 9adfb4b

Browse files
authored
Create StalinSort.java
1 parent 1c978c5 commit 9adfb4b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.thealgorithms.sorts;
2+
3+
/**
4+
* @author Anant Jain (https://github.com/anant-jain01)
5+
* @see https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420
6+
*/
7+
public class StalinSort implements SortAlgorithm {
8+
9+
public <T extends Comparable<T>> T[] sort(T[] array) {
10+
int currentIndex = 0;
11+
12+
for (int i = 1; i < array.length; i++) {
13+
if (array[i].compareTo(array[currentIndex]) >= 0) {
14+
currentIndex++;
15+
array[currentIndex] = array[i];
16+
}
17+
}
18+
19+
// Create a result array with sorted elements
20+
T[] result = (T[]) new Comparable[currentIndex + 1];
21+
System.arraycopy(array, 0, result, 0, currentIndex + 1);
22+
23+
return result;
24+
}
25+
26+
// Driver Program
27+
public static void main(String[] args) {
28+
// Integer Input
29+
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
30+
31+
StalinSort stalinSort = new StalinSort();
32+
33+
// print a sorted array
34+
SortUtils.print(stalinSort.sort(integers));
35+
36+
// String Input
37+
String[] strings = {"c", "a", "e", "b", "d"};
38+
39+
SortUtils.print(stalinSort.sort(strings));
40+
}
41+
}

0 commit comments

Comments
 (0)