1
1
package com .thealgorithms .sorts ;
2
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 {
3
+ import java .util .Arrays ;
8
4
5
+ public class StalinSort implements SortAlgorithm {
9
6
public <T extends Comparable <T >> T [] sort (T [] array ) {
7
+ validateInput (array );
10
8
int currentIndex = 0 ;
11
9
12
10
for (int i = 1 ; i < array .length ; i ++) {
@@ -16,26 +14,23 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
16
14
}
17
15
}
18
16
19
- // Create a result array with sorted elements
20
17
T [] result = (T []) new Comparable [currentIndex + 1 ];
21
18
System .arraycopy (array , 0 , result , 0 , currentIndex + 1 );
22
-
23
19
return result ;
24
20
}
25
21
26
- // Driver Program
22
+ private void validateInput (final Comparable <?>[] array ) {
23
+ if (array .length == 0 ) {
24
+ throw new IllegalArgumentException ("Input array must not be empty." );
25
+ }
26
+ }
27
+
27
28
public static void main (String [] args ) {
28
- // Integer Input
29
29
Integer [] integers = {4 , 23 , 6 , 78 , 1 , 54 , 231 , 9 , 12 };
30
-
31
30
StalinSort stalinSort = new StalinSort ();
32
-
33
- // print a sorted array
34
31
SortUtils .print (stalinSort .sort (integers ));
35
-
36
- // String Input
32
+
37
33
String [] strings = {"c" , "a" , "e" , "b" , "d" };
38
-
39
34
SortUtils .print (stalinSort .sort (strings ));
40
35
}
41
36
}
0 commit comments