forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrandSort.java
More file actions
79 lines (73 loc) · 2.43 KB
/
StrandSort.java
File metadata and controls
79 lines (73 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.thealgorithms.sorts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* StrandSort class implementing the SortAlgorithm interface using arrays.
*/
public final class StrandSort implements SortAlgorithm {
/**
* Sorts the given array using the Strand Sort algorithm.
*
* @param <T> The type of elements to be sorted, must be Comparable.
* @param array The array to be sorted.
* @return The sorted array.
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
List<T> unsortedList = new ArrayList<>(Arrays.asList(array));
List<T> sortedList = strandSort(unsortedList);
return sortedList.toArray(array);
}
/**
* Strand Sort algorithm that sorts a list.
*
* @param <T> The type of elements to be sorted, must be Comparable.
* @param list The list to be sorted.
* @return The sorted list.
*/
private static <T extends Comparable<? super T>> List<T> strandSort(List<T> list) {
if (list.size() <= 1) {
return list;
}
List<T> result = new ArrayList<>();
while (!list.isEmpty()) {
final List<T> sorted = new ArrayList<>();
sorted.add(list.removeFirst());
for (int i = 0; i < list.size();) {
if (sorted.getLast().compareTo(list.get(i)) <= 0) {
sorted.add(list.remove(i));
} else {
i++;
}
}
result = merge(result, sorted);
}
return result;
}
/**
* Merges two sorted lists into one sorted list.
*
* @param <T> The type of elements to be sorted, must be Comparable.
* @param left The first sorted list.
* @param right The second sorted list.
* @return The merged sorted list.
*/
private static <T extends Comparable<? super T>> List<T> merge(List<T> left, List<T> right) {
List<T> result = new ArrayList<>();
int i = 0;
int j = 0;
while (i < left.size() && j < right.size()) {
if (left.get(i).compareTo(right.get(j)) <= 0) {
result.add(left.get(i));
i++;
} else {
result.add(right.get(j));
j++;
}
}
result.addAll(left.subList(i, left.size()));
result.addAll(right.subList(j, right.size()));
return result;
}
}