forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStalinSort.java
More file actions
21 lines (20 loc) · 764 Bytes
/
StalinSort.java
File metadata and controls
21 lines (20 loc) · 764 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.thealgorithms.sorts;
public class StalinSort implements SortAlgorithm {
@SuppressWarnings("unchecked")
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
return array;
}
int currentIndex = 0;
for (int i = 1; i < array.length; i++) {
if (array[i].compareTo(array[currentIndex]) >= 0) {
currentIndex++;
array[currentIndex] = array[i];
}
}
// Create a result array with sorted elements
T[] result = (T[]) java.lang.reflect.Array.newInstance(array.getClass().getComponentType(), currentIndex + 1);
System.arraycopy(array, 0, result, 0, currentIndex + 1);
return result;
}
}