-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathAlgoVisualizer.java
96 lines (68 loc) · 2.04 KB
/
AlgoVisualizer.java
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.awt.*;
public class AlgoVisualizer {
private static int DELAY = 40;
private QuickSortData data;
private AlgoFrame frame;
public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
// 初始化数据
data = new QuickSortData(N, sceneHeight);
// 初始化视图
EventQueue.invokeLater(() -> {
frame = new AlgoFrame("Quick Sort Visualization", sceneWidth, sceneHeight);
new Thread(() -> {
run();
}).start();
});
}
public void run(){
setData(-1, -1, -1, -1, -1);
quickSort(0, data.N()-1);
setData(-1, -1, -1, -1, -1);
}
private void quickSort(int l, int r){
// if( l >= r )
// return;
if( l > r )
return;
if( l == r ){
setData(l, r, l, -1, -1);
return;
}
setData(l, r, -1, -1, -1);
int p = partition(l, r);
quickSort(l, p-1 );
quickSort(p+1, r);
}
private int partition(int l, int r){
int v = data.get(l);
setData(l, r, -1, l, -1);
int j = l; // arr[l+1...j] < v ; arr[j+1...i) > v
for( int i = l + 1 ; i <= r ; i ++ ){
setData(l, r, -1, l, i);
if( data.get(i) < v ){
j ++;
data.swap(j, i);
setData(l, r, -1, l, i);
}
}
data.swap(l, j);
setData(l, r, j, -1, -1);
return j;
}
private void setData(int l, int r, int fixedPivot, int curPivot, int curElement){
data.l = l;
data.r = r;
if(fixedPivot != -1)
data.fixedPivots[fixedPivot] = true;
data.curPivot = curPivot;
data.curElement = curElement;
frame.render(data);
AlgoVisHelper.pause(DELAY);
}
public static void main(String[] args) {
int sceneWidth = 800;
int sceneHeight = 800;
int N = 100;
AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N);
}
}