Skip to content

Commit 2f6cfa6

Browse files
committed
Add: java.util.List implements quick sort algorithm
1 parent 78179e9 commit 2f6cfa6

File tree

1 file changed

+64
-0
lines changed
  • src/test/java/com/github/anilople/javajvm/testcode/container

1 file changed

+64
-0
lines changed

src/test/java/com/github/anilople/javajvm/testcode/container/ListTest.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
import org.junit.jupiter.api.Test;
77

88
import java.util.ArrayList;
9+
import java.util.Arrays;
910
import java.util.List;
11+
import java.util.Objects;
1012

1113
import static org.junit.jupiter.api.Assertions.assertThrows;
1214
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -17,6 +19,68 @@
1719
*/
1820
class ListTest {
1921

22+
public static void main(String[] args) {
23+
runQuickSort();
24+
}
25+
26+
static <T> List<T> concat(List<T> ... lists) {
27+
List<T> all = new ArrayList<>();
28+
for(List<T> list : lists) {
29+
all.addAll(list);
30+
}
31+
return all;
32+
}
33+
34+
static <T extends Comparable<T>> List<T> quickSort(List<T> list) {
35+
Objects.requireNonNull(list);
36+
if(list.size() <= 1) {
37+
return new ArrayList<>(list);
38+
}
39+
40+
List<T> smaller = new ArrayList<>();
41+
List<T> equal = new ArrayList<>();
42+
List<T> bigger = new ArrayList<>();
43+
44+
T midValue = list.get(0);
45+
for(T now : list) {
46+
if(now.compareTo(midValue) < 0) {
47+
smaller.add(now);
48+
} else if(now.compareTo(midValue) == 0) {
49+
equal.add(now);
50+
} else {
51+
bigger.add(now);
52+
}
53+
}
54+
55+
return concat(
56+
quickSort(smaller),
57+
equal,
58+
quickSort(bigger)
59+
);
60+
}
61+
62+
private static void runQuickSort() {
63+
List<Integer> list = Arrays.asList(
64+
5, -3, 1, 200, 0, -10, 100, 2
65+
);
66+
System.out.println("before sort: " + list);
67+
List<Integer> sorted = quickSort(list);
68+
System.out.println("after sort: " + sorted);
69+
}
70+
71+
@Test
72+
void runQuickSortTest() {
73+
JvmThreadRunner jvmThreadRunner = new JvmThreadRunner(
74+
JvmThreadFactory.createFromStaticMethod(
75+
this.getClass(),
76+
"runQuickSort",
77+
"()V"
78+
)
79+
);
80+
81+
jvmThreadRunner.run();
82+
}
83+
2084
static void add() {
2185
List<Integer> list = new ArrayList<>();
2286
list.add(1);

0 commit comments

Comments
 (0)