-
Notifications
You must be signed in to change notification settings - Fork 173
/
AlgoVisualizer.java
78 lines (54 loc) · 1.58 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
import java.awt.*;
public class AlgoVisualizer {
private static int DELAY = 20;
private HeapSortData data;
private AlgoFrame frame;
public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
// 初始化数据
data = new HeapSortData(N, sceneHeight);
// 初始化视图
EventQueue.invokeLater(() -> {
frame = new AlgoFrame("Heap Sort Visualization", sceneWidth, sceneHeight);
new Thread(() -> {
run();
}).start();
});
}
public void run(){
setData(data.N());
// 建堆
for( int i = (data.N()-1-1)/2 ; i >= 0 ; i -- ){
shiftDown(data.N(), i);
}
// 堆排序
for( int i = data.N()-1; i > 0 ; i-- ){
data.swap(0, i);
shiftDown(i, 0);
setData(i);
}
setData(0);
}
private void shiftDown(int n, int k){
while( 2*k+1 < n ){
int j = 2*k+1;
if( j+1 < n && data.get(j+1) > data.get(j) )
j += 1;
if( data.get(k) >= data.get(j) )
break;
data.swap(k, j);
setData(data.heapIndex);
k = j;
}
}
private void setData(int heapIndex){
data.heapIndex = heapIndex;
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);
}
}